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

const DEFAULT_ORG_ID = 'e47e6210-4879-4e5b-bf21-9285d2713123';

export const createPart = async (data: any) => {
    const orgId = data.organization_id || data.organizationId || DEFAULT_ORG_ID;
    return await Part.create({ ...data, organization_id: orgId });
};

export const getPartsByProject = async (projectId: string, organizationId?: string, isGlobalAdmin: boolean = false) => {
    const filter: any = { project_id: projectId };
    if (!isGlobalAdmin && organizationId) {
        filter.organization_id = organizationId;
    }
    return await Part.find(filter);
};

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

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.organization_id && existing.organization_id !== organizationId) {
        console.warn(`Access Denied: Part ${id} belongs to ${existing.organization_id}, user is ${organizationId}`);
        return null;
    }

    return await Part.findByIdAndUpdate(id, data);
};

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

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

