import { ApplicationRecord } from '../lib/compat.js';

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

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const createApplicationRecord = async (data: any) => {
    const orgId = data.organization_id || data.organizationId || DEFAULT_ORG_ID;
    const record = await ApplicationRecord.create({
        ...data,
        date: data.date ? new Date(data.date).toISOString() : null,
        organization_id: orgId,
        created_by: data.createdBy || data.created_by,
        project_id: data.projectId || data.project_id
    });
    return record;
};

export const getApplicationRecordsByProject = async (projectId: string, organizationId?: string) => {
    const filter: any = { project_id: projectId };
    if (organizationId) {
        filter.organization_id = organizationId;
    }
    return await ApplicationRecord.find(filter);
};

// 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.organization_id && existing.organization_id !== organizationId) {
        return null;
    }

    // Role/Ownership check
    const isPowerUser = userRole === 'admin' || isDeveloper;
    if (!isPowerUser && existing.created_by && existing.created_by !== userId) {
        console.warn(`Permission Denied: User ${userId} tried to update record ${id} created by ${existing.created_by}`);
        return null;
    }

    const updateData = {
        ...data,
        date: data.date ? new Date(data.date).toISOString() : undefined
    };

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

    return await ApplicationRecord.findByIdAndUpdate(id, updateData);
};

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.organization_id && existing.organization_id !== organizationId) {
        return false;
    }

    // Role/Ownership check
    const isPowerUser = userRole === 'admin' || isDeveloper;
    if (!isPowerUser && existing.created_by && existing.created_by !== userId) {
        return false;
    }

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

