import ExternalInvoiceModel from "./externalInvoice.model";

import { IExternalInvoice } from "./externalInvoice.interface";

export class ExternalInvoiceService {

    //Crear factura externa

    async create(
        data: IExternalInvoice
    ) {

        // Calcular monto total
        data.totalAmount =
            data.gallons *
            data.pricePerGallon;
        const invoice =
            new ExternalInvoiceModel(data);

        return await invoice.save();

    }

    //Obtener todas las facturas
     
    async getAll() {

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

    }

    // Obtener factura por ID
    
    async getById(
        id: string
    ) {

        return await ExternalInvoiceModel
            .findById(id)
            .populate("fuelTypeId")
            .populate("createdBy")
            .populate("approvedBy");

    }

    //Actualizar factura
     
    async update(
        id: string,
        data: Partial<IExternalInvoice>
    ) {

        // Recalcular total si cambian datos
        if (
            data.gallons &&
            data.pricePerGallon
        ) {

            data.totalAmount =
                data.gallons *
                data.pricePerGallon;

        }

        return await ExternalInvoiceModel
            .findByIdAndUpdate(
                id,
                data,
                {
                    new: true
                }
            );

    }

    // Buscar por estado
     
    async getByStatus(
        status: string
    ) {

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

    }

    // Buscar por zona
    
    async getByZone(
        zone: string
    ) {

        return await ExternalInvoiceModel
            .find({
                zone
            } as any);

    }

    //Eliminar factura
    
    async delete(
        id: string
    ) {

        return await ExternalInvoiceModel
            .findByIdAndDelete(id);

    }

}