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

const { SystemConfiguration } = db;

export type AutoAssignmentModule =
    | 'ONBOARDING'
    | 'RELOCATION'
    | 'TERMINATION'
    | 'RESIGNATION'
    | 'CONSTITUTIONAL'
    | 'FNF';

const MODULE_CONFIG_KEYS: Record<AutoAssignmentModule, string> = {
    ONBOARDING: 'AUTO_ASSIGN_ONBOARDING',
    RELOCATION: 'AUTO_ASSIGN_RELOCATION',
    TERMINATION: 'AUTO_ASSIGN_TERMINATION',
    RESIGNATION: 'AUTO_ASSIGN_RESIGNATION',
    CONSTITUTIONAL: 'AUTO_ASSIGN_CONSTITUTIONAL',
    FNF: 'AUTO_ASSIGN_FNF'
};

/**
 * Check if auto-assignment is enabled for a given module.
 * Returns true by default if config is missing (backward compatible).
 */
export async function isAutoAssignmentEnabled(module: AutoAssignmentModule): Promise<boolean> {
    try {
        const key = MODULE_CONFIG_KEYS[module];
        const config = await SystemConfiguration.findOne({
            where: { key, isActive: true }
        });

        if (!config) {
            console.log(`[AutoAssignmentConfig] Config ${key} not found, defaulting to enabled`);
            return true;
        }

        const value = config.value || {};
        // Support both { enabled: boolean } and legacy boolean values
        const enabled = typeof value.enabled === 'boolean' ? value.enabled : Boolean(value);
        return enabled;
    } catch (error) {
        console.error(`[AutoAssignmentConfig] Error checking ${module}:`, error);
        return true; // Fail open for safety
    }
}

/**
 * Get status for all modules at once (useful for admin dashboards)
 */
export async function getAllAutoAssignmentStatuses(): Promise<Record<AutoAssignmentModule, boolean>> {
    const result: Record<string, boolean> = {};

    try {
        const configs = await SystemConfiguration.findAll({
            where: {
                key: Object.values(MODULE_CONFIG_KEYS),
                isActive: true
            }
        });

        const configMap = new Map(configs.map((c: any) => [c.key, c.value]));

        for (const [module, key] of Object.entries(MODULE_CONFIG_KEYS)) {
            const value = (configMap.get(key) || {}) as { enabled?: boolean };
            result[module] = typeof value.enabled === 'boolean' ? value.enabled : true;
        }
    } catch (error) {
        console.error('[AutoAssignmentConfig] Error fetching all statuses:', error);
        // Default all to true on error
        for (const module of Object.keys(MODULE_CONFIG_KEYS)) {
            result[module] = true;
        }
    }

    return result as Record<AutoAssignmentModule, boolean>;
}

/**
 * Get module name from requestType string (used in ParticipantService)
 */
export function getModuleFromRequestType(requestType: string): AutoAssignmentModule | null {
    const mapping: Record<string, AutoAssignmentModule> = {
        'application': 'ONBOARDING',
        'relocation': 'RELOCATION',
        'termination': 'TERMINATION',
        'resignation': 'RESIGNATION',
        'constitutional': 'CONSTITUTIONAL',
        'fnf': 'FNF'
    };
    return mapping[requestType.toLowerCase()] || null;
}
