import { YieldStudy, TechnicalDataSheet } from '../lib/compat.js';

export const getAllStudies = async (organizationId?: string) => {
    const query = organizationId ? { organizationId } : {};
    // Compatibility layer handles .find() and returns plain objects with id
    const studies = await YieldStudy.find(query);
    
    // Attempt manual population if dataSheetId exists
    return await Promise.all(studies.map(async (s: any) => {
        if (s.dataSheetId) {
            const dataSheet = await TechnicalDataSheet.findById(s.dataSheetId);
            return { ...s, dataSheetId: dataSheet || s.dataSheetId };
        }
        return s;
    }));
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const createStudy = async (data: any & { organizationId?: string }) => {
    const saved = await YieldStudy.create({ ...data, organizationId: data.organizationId });
    return saved;
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const updateStudy = async (id: string, updates: any, organizationId?: string) => {
    const existing = await YieldStudy.findById(id);
    if (!existing) return null;

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

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

    const updated = await YieldStudy.findOneAndUpdate({ id }, updates);
    return updated;
};

export const deleteStudy = async (id: string, organizationId?: string) => {
    const existing = await YieldStudy.findById(id);
    if (!existing) return false;

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

    await YieldStudy.findByIdAndDelete(id);
    return true;
};
