const ExecutivesHistoryRepository = require('../../repository/sales/ExecutivesHistoryRepository.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.getAllExecutivesHistoryService = 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([
        ExecutivesHistoryRepository.findAll({ skip, take: limit, where, orderBy: { [sortBy]: orderBy } }),
        ExecutivesHistoryRepository.countAll(where)
    ]);

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

    return { vendor_histories: formatted, total };
};

exports.showExecutivesHistoryService = async (req) => {
    const id_hospital = req.params.id;
    const id_executives_history = req.params.id_executives_history;

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

    const executivesHistory = await ExecutivesHistoryRepository.findById(id_executives_history);
    if (!executivesHistory) {
        throw new HttpException("Executives history not found", 404);
    }

    return {
        ...executivesHistory,
        start_term: formatDateOnly(executivesHistory.start_term),
        end_term: formatDateOnly(executivesHistory.end_term),
        createdAt: formatISOWithoutTimezone(executivesHistory.createdAt),
        updatedAt: formatISOWithoutTimezone(executivesHistory.updatedAt),
    };
};

exports.storeExecutivesHistoryService = 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)
    }

    const payload = {
        ...validateData,
        hospital_id: hospitalId
    };

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

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

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

    const executivesHistory = await ExecutivesHistoryRepository.findById(id_executives_history);
    if (!executivesHistory) {
        throw new HttpException("Executives history not found", 404);
    }

    const payload = {
        ...validateData
    };

    const data = await ExecutivesHistoryRepository.update(id_executives_history, payload);
    await updateLog(req, data);
};

exports.deleteExecutivesHistoryService = async (req) => {
    const id_hospital = req.params.id;
    const id_executives_history = req.params.id_executives_history;

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

    const executivesHistory = await ExecutivesHistoryRepository.findById(id_executives_history);
    if (!executivesHistory) {
        throw new HttpException("Executives history not found", 404);
    }

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

    await deleteLog(req, data);
};