import ApprovalModel from "./approval.model";

import FuelRequestModel from "../fuel-requests/fuelRequest.model";

import externalInvoiceModel from "../external-invoices/externalInvoice.model";

import lpgModel from "../lpg/lpg.model";

import { IApproval } from "./approval.interface";


export class ApprovalService {

    //Obtener todas las aprobaciones
    
    async getAll() {

        return await ApprovalModel
            .find()
            .populate("approvedBy")
            .sort({
                createdAt: -1
            });

    }

    //Obtener aprobación por ID

    async getById(
        id: string
    ) {

        return await ApprovalModel
            .findById(id)
            .populate("approvedBy");

    }

    //Crear aprobación

    async create(
        data: IApproval
    ) {

        const approval =
            new ApprovalModel(data);

        return await approval.save();

    }

    //
    async approve(
        approvalId: string,
        approvedBy: string,
        comments?: string
    ) {

        // Buscar aprobación
        const approval =
            await ApprovalModel.findById(
                approvalId
            );

        if (!approval) {

            throw new Error(
                "Aprobación no encontrada"
            );

        }

        // Actualizar aprobación
        approval.status =
            "APROBADO";

        approval.approvedBy =
            approvedBy as any;

        approval.approvedDate =
            new Date();

        approval.comments =
            comments || "";

        await approval.save();

        if (
            approval.referenceType ===
            "FuelRequest"
        ) {

            await FuelRequestModel
                .findByIdAndUpdate(

                    approval.referenceId,

                    {
                        status:
                        "APROBADO"
                    },

                    {
                        new: true
                    }

                );

        }

        if (
            approval.referenceType ===
            "ExternalInvoice"
        ) {

            await externalInvoiceModel
                .findByIdAndUpdate(

                    approval.referenceId,

                    {
                        status:
                        "APROBADO"
                    },

                    {
                        new: true
                    }

                );

        }

        if (
            approval.referenceType ===
            "LPG"
        ) {

            await lpgModel
                .findByIdAndUpdate(

                    approval.referenceId,

                    {
                        status:
                        "APROBADO"
                    },

                    {
                        new: true
                    }

                );
            }
  

        return approval;

    }

    //Rechazar solicitud
    
    async reject(
        approvalId: string,
        approvedBy: string,
        comments?: string
    ) {

        // Buscar aprobación
        const approval =
            await ApprovalModel.findById(
                approvalId
            );

        if (!approval) {

            throw new Error(
                "Aprobación no encontrada"
            );

        }

        // Actualizar aprobación
        approval.status =
            "RECHAZADO";

        approval.approvedBy =
            approvedBy as any;

        approval.approvedDate =
            new Date();

        approval.comments =
            comments || "";

        await approval.save();

        if (
            approval.referenceType ===
            "FuelRequest"
        ) {

            await FuelRequestModel
                .findByIdAndUpdate(

                    approval.referenceId,

                    {
                        status:
                        "RECHAZADO"
                    },

                    {
                        new: true
                    }

                );

        }

        if (
            approval.referenceType ===
            "ExternalInvoice"
        ) {

            await externalInvoiceModel
                .findByIdAndUpdate(

                    approval.referenceId,

                    {
                        status:
                        "RECHAZADO"
                    },

                    {
                        new: true
                    }

                );

        }
    
        if (
            approval.referenceType ===
            "LPG"
        ) {

            await lpgModel
                .findByIdAndUpdate(

                    approval.referenceId,

                    {
                        status:
                        "RECHAZADO"
                    },

                    {
                        new: true
                    }

                );
        }

        return approval;

    }

    //Obtener aprobaciones por estado
    
    async getByStatus(
        status: string
    ) {

        return await ApprovalModel.find({
            status
        } as any);

    }

    //Obtener aprobaciones por tipo de referencia
    
    async getByReferenceType(
        referenceType: string
    ) {

        return await ApprovalModel.find({
            referenceType
        } as any);

    }

    //Eliminar aprobación
    
    async delete(
        id: string
    ) {

        return await ApprovalModel
            .findByIdAndDelete(id);

    }

}