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

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const createPart = async (data: any & { organizationId?: string }) => {
    const newPart = new Part({ ...data, organizationId: data.organizationId });
    const saved = await newPart.save();
    return { ...saved.toObject(), id: saved._id.toString() };
};

export const getPartsByProject = async (projectId: string, organizationId?: string, isGlobalAdmin: boolean = false) => {
    const query = isGlobalAdmin
        ? { projectId }
        : { projectId, $or: [{ organizationId }, { organizationId: { $exists: false } }, { organizationId: null }] };
    const parts = await Part.find(query).lean();
    return parts.map(p => ({ ...p, id: p._id.toString() }));
};

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

    if (!isGlobalAdmin && organizationId && existing.organizationId && existing.organizationId !== organizationId) {
        console.warn(`Access Denied: Part ${id} belongs to ${existing.organizationId}, user is ${organizationId}`);
        return null;
    }

    if (organizationId && !existing.organizationId) {
        data.organizationId = organizationId; // Adopt
    }

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

export const deletePart = async (id: string, organizationId?: string, isGlobalAdmin: boolean = false) => {
    const part = await Part.findById(id);
    if (!part) return;

    if (!isGlobalAdmin && organizationId && part.organizationId && part.organizationId !== organizationId) {
        throw new Error('Sem permissão para excluir esta peça');
    }

    await Part.findByIdAndDelete(id);
};

export const getAllParts = async (organizationId?: string, isGlobalAdmin: boolean = false) => {
    const query = isGlobalAdmin
        ? {}
        : { $or: [{ organizationId }, { organizationId: { $exists: false } }, { organizationId: null }] };
    const parts = await Part.find(query).lean();
    return parts.map(p => ({ ...p, id: p._id.toString() }));
};



