import { Inspection, findOneGpi, queryGpi } from '../lib/compat.js';

export const createInspection = async (data: any & { organizationId?: string, createdBy?: string }) => {
    return await Inspection.create({
        ...data,
        date: data.date ? new Date(data.date).toISOString() : null,
        organization_id: data.organizationId,
        created_by: data.createdBy
    });
};

export const getInspectionsByProject = async (projectId: string, organizationId?: string) => {
    const filter: any = { project_id: projectId };
    if (organizationId) {
        filter.organization_id = organizationId;
    }
    return await Inspection.find(filter);
};

export const getInspectionById = async (id: string) => {
    return await Inspection.findById(id);
};

export const updateInspection = async (id: string, data: any) => {
    return await Inspection.findByIdAndUpdate(id, data);
};

export const deleteInspection = async (id: string) => {
    return await Inspection.findByIdAndDelete(id);
};

export const getInspectionsByOrganization = async (organizationId: string) => {
    return await Inspection.find({ organization_id: organizationId });
};

export const getInspectionStats = async (organizationId?: string) => {
    const filter = organizationId ? { organization_id: organizationId } : {};
    const inspections = await Inspection.find(filter);
    return {
        total: inspections.length,
        inspections
    };
};

console.log('✅ InspectionService loaded with compatibility');
