import vehicleassigModel from "./vehicleassig.model";
import { IVehicleAssig } from './vehicleassig.interface';


export class VehicleAssigService {

    async getAll()
    {

        return await vehicleassigModel
        .find()
        .populate(
            "createdBy",
            "userName"
        );
    }

    async getById(
        id:string
    ){
        return await vehicleassigModel
        .findById(id)
        .populate(
            "createdBy",
            "userName"
        );
    }

    async create(
        data:IVehicleAssig
    ){

        const assig = await vehicleassigModel.findOne({
            vehicleNumber: data.vehicleNumber,
            active:true
        });

        if(assig){
            throw new Error ("El vehículo ya tiene una asignación activa");
        }

        return await vehicleassigModel.create(
            data
        );
    }

    async update(
        id:string,
        data:Partial<IVehicleAssig>
    ){

        if(data.vehicleNumber !== undefined){
           
            const assig = await vehicleassigModel.findOne({
                vehicleNumber: data.vehicleNumber,
                active:true,
                _id: { $ne: id }
            });

            if(assig){
                throw new Error("El vehículo ya tiene asignación activa");
            }
        }

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

    async delete(
        id:string
    ){
        return await vehicleassigModel.findByIdAndDelete(
            id
        );
    }
}