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

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

export const getApplicationRecordsByProject = async (projectId: string, organizationId?: string) => {
    const query = { projectId, ...(organizationId ? { organizationId } : {}) };
    const records = await ApplicationRecord.find(query).sort({ date: -1 }).lean();
    return records.map(r => ({ ...r, id: r._id.toString() }));
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const updateApplicationRecord = async (id: string, data: any, organizationId?: string, userId?: string, userRole?: string, isDeveloper: boolean = false) => {
    const existing = await ApplicationRecord.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 record ${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 ApplicationRecord.findOneAndUpdate({ _id: id }, updateData, { new: true }).lean();
    if (updated) {
        return { ...updated, id: updated._id.toString() };
    }
    return null;
};

export const deleteApplicationRecord = async (id: string, organizationId?: string, userId?: string, userRole?: string, isDeveloper: boolean = false) => {
    const existing = await ApplicationRecord.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 ApplicationRecord.deleteOne({ _id: id });
    return true;
};
