import db from '../database/models/index.js';

const { AuditLog } = db;

/** Fields that help explain pipeline / FDD / statutory state without large payloads */
export function pickApplicationAuditContext(app: any): Record<string, unknown> {
    if (!app) return {};
    return {
        applicationHumanId: app.applicationId ?? null,
        overallStatus: app.overallStatus ?? null,
        currentStage: app.currentStage ?? null,
        progressPercentage: app.progressPercentage ?? null,
        statutoryStatus: app.statutoryStatus ?? null,
        architectureStatus: app.architectureStatus ?? null,
        isShortlisted: app.isShortlisted ?? null,
        opportunityId: app.opportunityId ?? null,
    };
}

export type SafeAuditPayload = {
    userId?: string | null;
    action: string;
    entityType: string;
    entityId: string;
    oldData?: Record<string, unknown> | null;
    newData?: Record<string, unknown> | null;
};

/**
 * Writes an audit row and never throws — avoids breaking sensitive workflows
 * (status transitions, prospective uploads, finance verification) if audit storage fails.
 */
export async function safeAuditLogCreate(payload: SafeAuditPayload): Promise<void> {
    try {
        await AuditLog.create(payload as any);
    } catch (err) {
        console.error('[safeAuditLogCreate] Non-fatal audit failure:', (err as Error)?.message || err);
    }
}
