import Inspection from '../models/Inspection.js';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const createInspection = async (data: any & { organizationId?: string, createdBy?: string }) => {
    const newInspection = new Inspection({
        ...data,
        date: data.date ? new Date(data.date) : null,
        organizationId: data.organizationId,
        createdBy: data.createdBy
    });
    const saved = await newInspection.save();
    return { ...saved.toObject(), id: saved._id.toString() };
};

export const getInspectionsByProject = async (projectId: string, organizationId?: string) => {
    const query = { projectId, ...(organizationId ? { organizationId } : {}) };
    const inspections = await Inspection.find(query).sort({ date: -1 }).lean();
    return inspections.map(i => ({ ...i, id: i._id.toString() }));
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const updateInspection = async (id: string, data: any, organizationId?: string, userId?: string, userRole?: string, isDeveloper: boolean = false) => {
    const existing = await Inspection.findById(id);
    if (!existing) return null;

    // Organization Check
    if (organizationId && existing.organizationId && existing.organizationId !== organizationId) {
        return null;
    }

    // Role/Ownership check
    const isPowerUser = userRole === 'admin' || isDeveloper;
    if (!isPowerUser && existing.createdBy && existing.createdBy !== userId) {
        console.warn(`Permission Denied: User ${userId} tried to update inspection ${id} created by ${existing.createdBy}`);
        return null;
    }

    const updateData = {
        ...data,
        date: data.date ? new Date(data.date) : undefined
    };

    if (organizationId && !existing.organizationId) {
        updateData.organizationId = organizationId;
    }

    const updated = await Inspection.findOneAndUpdate({ _id: id }, updateData, { new: true }).lean();
    if (updated) {
        return { ...updated, id: updated._id.toString() };
    }
    return null;
};

export const deleteInspection = async (id: string, organizationId?: string, userId?: string, userRole?: string, isDeveloper: boolean = false) => {
    const existing = await Inspection.findById(id);
    if (!existing) return false;

    // Organization Check
    if (organizationId && existing.organizationId && existing.organizationId !== organizationId) {
        return false;
    }

    // Role/Ownership check
    const isPowerUser = userRole === 'admin' || isDeveloper;
    if (!isPowerUser && existing.createdBy && existing.createdBy !== userId) {
        return false;
    }

    await Inspection.deleteOne({ _id: id });
    return true;
};

export const getAllInspections = async (organizationId?: string) => {
    const query = organizationId ? { organizationId } : {};
    const inspections = await Inspection.find(query).lean();
    return inspections.map(i => ({ ...i, id: i._id.toString() }));
};



