const VendorHistoryRepository = require('../../repository/admin/VendorHistoryRepository.js');
const HttpException = require('../../utils/HttpException.js');
const prisma = require('../../prisma/PrismaClient.js');
const { SearchFilter } = require('../../utils/SearchFilter.js');
const timeLocal = require('../../utils/TimeLocal.js');
const { createLog, updateLog, deleteLog } = require('../../utils/LogActivity.js');
const { formatDateOnly, formatISOWithoutTimezone } = require('../../utils/FormatDate.js');

exports.getAllVendorHistoryService = async ({ page, limit, search, sortBy, orderBy }, req) => {
    const skip = (page - 1) * limit;

    const hospitalId = req.params.id;
    const hospital = await prisma.hospital.findFirst({
        where: {
            id: hospitalId
        }
    })
    if (!hospital) {
        throw new HttpException("Hospital not found", 404)
    }

    const where = {
        // ...SearchFilter(search, ['name', 'name_pt']),
        hospital_id: req.params.id,
        deletedAt: null
    };

    const [vendor_histories, total] = await Promise.all([
        VendorHistoryRepository.findAll({ skip, take: limit, where, orderBy: { [sortBy]: orderBy } }),
        VendorHistoryRepository.countAll(where)
    ]);

    const formatted = vendor_histories.map(v => ({
        ...v,
        contract_date: formatDateOnly(v.contract_date),
        contract_expired_date: formatDateOnly(v.contract_expired_date),
        createdAt: formatISOWithoutTimezone(v.createdAt),
        updatedAt: formatISOWithoutTimezone(v.updatedAt),
    }));

    return { vendor_histories: formatted, total };
};

exports.showVendorHistoryService = async (req) => {
    const id_hospital = req.params.id;
    const id_vendor_history = req.params.id_vendor_history;

    const hospital = await prisma.hospital.findFirst({
        where: {
            id: id_hospital
        }
    })
    if (!hospital) {
        throw new HttpException("Hospital not found", 404)
    }

    const vendorHistory = await VendorHistoryRepository.findById(id_vendor_history);
    if (!vendorHistory) {
        throw new HttpException("Vendor history not found", 404);
    }

    return {
        ...vendorHistory,
        contract_date: formatDateOnly(vendorHistory.contract_date),
        contract_expired_date: formatDateOnly(vendorHistory.contract_expired_date),
        createdAt: formatISOWithoutTimezone(vendorHistory.createdAt),
        updatedAt: formatISOWithoutTimezone(vendorHistory.updatedAt),
    };
};

exports.storeVendorHistoryService = async (validateData, req) => {
    const hospitalId = req.params.id;

    const hospital = await prisma.hospital.findFirst({
        where: {
            id: hospitalId
        }
    })
    if (!hospital) {
        throw new HttpException("Hospital not found", 404)
    }

    await prisma.hospital.update({
        where: { id: hospitalId },
        data: {
            simrs_type: validateData.simrs_type
        }
    });

    const payload = {
        vendor_id: validateData.vendor_id,
        vendor_impression: validateData.vendor_impression,
        status: validateData.status,
        contract_date: validateData.contract_date,
        contract_expired_date: validateData.contract_expired_date,
        hospital_id: hospitalId
    };

    const data = await VendorHistoryRepository.create(payload);
    await createLog(req, data);
};

exports.updateVendorHistoryService = async (validateData, req) => {
    const id_hospital = req.params.id;
    const id_vendor_history = req.params.id_vendor_history;

    const hospital = await prisma.hospital.findFirst({
        where: {
            id: id_hospital
        }
    })
    if (!hospital) {
        throw new HttpException("Hospital not found", 404)
    }

    const vendor = await VendorHistoryRepository.findById(id_vendor_history);
    if (!vendor) {
        throw new HttpException("Vendor history not found", 404);
    }

    await prisma.hospital.update({
        where: { id: id_hospital },
        data: {
            simrs_type: validateData.simrs_type
        }
    });

    const payload = {
        vendor_id: validateData.vendor_id,
        vendor_impression: validateData.vendor_impression,
        status: validateData.status,
        contract_date: validateData.contract_date,
        contract_expired_date: validateData.contract_expired_date
    };

    const data = await VendorHistoryRepository.update(id_vendor_history, payload);
    await updateLog(req, data);
};

exports.deleteVendorHistoryService = async (req) => {
    const id_hospital = req.params.id;
    const id_vendor_history = req.params.id_vendor_history;

    const hospital = await prisma.hospital.findFirst({
        where: {
            id: id_hospital
        }
    })
    if (!hospital) {
        throw new HttpException("Hospital not found", 404)
    }

    const vendor = await VendorHistoryRepository.findById(id_vendor_history);
    if (!vendor) {
        throw new HttpException("Vendor history not found", 404);
    }

    const data = await VendorHistoryRepository.update(id_vendor_history, {
        deletedAt: timeLocal.now().toDate()
    });

    await deleteLog(req, data);
};