import anomalyModel from "./anomaly.model";
import { IAnomaly } from "./anomaly.interface";

export class AnomalyService{

    //Crear anomalía
    async create(
        data:IAnomaly
    ){
        const anomaly = new anomalyModel(data);

        return await anomaly.save();
    }

    //Obtener anomalía
    async getAll() {

        return await anomalyModel
        .find()
        .populate("reportedBy")
        .populate("resolvedBy")
        .sort({
            createdAt:-1
        });
        
    }

    async getById(
        id:string
    ){
        return await anomalyModel
        .findById(id)
        .populate("reportedBy")
        .populate("resolvedBy")
    }

    //Actualizar 
    async update(
        id:string,
        data:Partial<IAnomaly>
    ){
        return await anomalyModel.findByIdAndUpdate(
            id,
            data,
            {
                new:true
            }
        )
    }

    //Cambiar estado

    async changeStatus(
        id:string,
        status:string
    ){
        return await anomalyModel.findByIdAndUpdate(
            id,
            {
                status
            },
            {
                new:true
            }
        );
    }

    //Cerrar anomalía

    async close(
        id:string,
        resolvedBy:string,
        comments?:String
    ){
        return await anomalyModel.findByIdAndUpdate(
            id,
            {
                status:"CERRADA",
                resolvedBy,
                resolvedDate: new Date(),
                comments
            },
            {
                new:true
            }
        );
    }

    async getByStatus(
        status:string
    ){
        return await anomalyModel.find({
            status
        } as any);
    }

    async getByType(
        anomalyType:string
    ){
        return await anomalyModel.find({
            anomalyType
        } as any);
    }

    async getByVehicle(
        vehicleId:number
    ){
        return await anomalyModel.find({
            vehicleId
        } as any);
    }

     async getByEmployee(
        employeeId:number
    ){
        return await anomalyModel.find({
            employeeId
        } as any);
    }

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

}