import fuelRequestModel from "./fuelRequest.model";
import { IFuelRequest } from "./fuelRequest.interface";

import { generateRequestNumber } from "../../utils/requestNumber";

export class FuelRequestService {
    //Obtener todas las requisiciones

    async getAll() {
        return await fuelRequestModel
            .find()
            .populate("fuelPumpId")
            .populate("fuelTypeId")
            .populate("createdBy")
            .populate("authorizedBy")
            .sort({ createdAt: -1 });
    }

    //Obtener reauisición por ID

    async getById(
        id:string
    ) {

        return await fuelRequestModel
            .findById(id)
            .populate("fuelPumpId")
            .populate("fuelTypeId")
            .populate("createdBy")
            .populate("authorizedBy");

    }

    //Crear una nueva requisición

    async create (
        data:IFuelRequest
    ){
        //Generar número automático
        data.requestNumber = generateRequestNumber();

        //Calcular distancia recorrida
        data.distanceTraveled = data.currentMileage - data.previousMileage;

        //Calcular monto total
        data.totalAmount = data.gallonQuantity * data.pricePerGallon;

        //Estado inicial
        data.status = "PENDIENTE";

        //Crear documento
        const request = new fuelRequestModel(data);

        //Guardar en DB
        return await request.save();

    }

    async update(
        id:string,
        data:Partial<IFuelRequest>
    ){
        //Recalcular distancia
        if(data.currentMileage !== undefined &&
            data.previousMileage !== undefined
        ){
            data.distanceTraveled =
            data.currentMileage -
            data.previousMileage;
        }

        //Recalcular monto
        if(
            data.gallonQuantity !== undefined &&
            data.pricePerGallon !== undefined
        ){
            data.totalAmount =
            data.gallonQuantity *
            data.pricePerGallon;
        }

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

    //Eliminar requisición

    async delete(
        id:string
    ){

        return await fuelRequestModel
        .findByIdAndDelete(id);
    }
}