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

export const getAllStudies = async (organizationId?: string) => {
    const query = organizationId ? { organizationId } : {};
    const studies = await YieldStudy.find(query).populate('dataSheetId').sort({ createdAt: -1 }).lean();
    return studies.map(s => ({ ...s, id: s._id.toString() }));
};

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

// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const updateStudy = async (id: string, updates: any, organizationId?: string) => {
    // SECURITY FIX: Allow update if:
    // 1. Matches ID AND Matches Organization
    // 2. OR Matches ID AND Record has NO organization (legacy/orphan) -> Adopt it!

    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: id }, updates, { new: true }).lean();
    if (updated) {
        return { ...updated, id: updated._id.toString() };
    }
    return null;
};

export const deleteStudy = async (id: string, organizationId?: string) => {
    // SECURITY FIX: Same logic as update - allow delete if owned OR if orphan
    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;
};


