/**
 * Seed script for per-module auto-assignment configuration settings.
 * Run: npx ts-node scripts/seed-auto-assignment-configs.ts
 */
import db from '../src/database/models/index.js';

const { SystemConfiguration } = db;

const AUTO_ASSIGNMENT_CONFIGS = [
    {
        key: 'AUTO_ASSIGN_ONBOARDING',
        value: { enabled: true },
        category: 'WORKFLOW_SETTINGS',
        description: 'Enable/disable automatic participant assignment for Onboarding module (DD, Interviews, LOI, LOA stages)'
    },
    {
        key: 'AUTO_ASSIGN_RELOCATION',
        value: { enabled: true },
        category: 'WORKFLOW_SETTINGS',
        description: 'Enable/disable automatic participant assignment for Relocation requests'
    },
    {
        key: 'AUTO_ASSIGN_TERMINATION',
        value: { enabled: true },
        category: 'WORKFLOW_SETTINGS',
        description: 'Enable/disable automatic participant assignment for Termination requests'
    },
    {
        key: 'AUTO_ASSIGN_RESIGNATION',
        value: { enabled: true },
        category: 'WORKFLOW_SETTINGS',
        description: 'Enable/disable automatic participant assignment for Resignation requests'
    },
    {
        key: 'AUTO_ASSIGN_CONSTITUTIONAL',
        value: { enabled: true },
        category: 'WORKFLOW_SETTINGS',
        description: 'Enable/disable automatic participant assignment for Constitutional Change requests'
    },
    {
        key: 'AUTO_ASSIGN_FNF',
        value: { enabled: true },
        category: 'WORKFLOW_SETTINGS',
        description: 'Enable/disable automatic participant assignment for F&F Settlement requests'
    }
];

async function seedAutoAssignmentConfigs() {
    try {
        console.log('[seed-auto-assignment] Starting...');

        for (const config of AUTO_ASSIGNMENT_CONFIGS) {
            const [record, created] = await SystemConfiguration.findOrCreate({
                where: { key: config.key },
                defaults: {
                    ...config,
                    isActive: true
                }
            });

            if (created) {
                console.log(`[seed-auto-assignment] Created: ${config.key}`);
            } else {
                // Ensure value structure is correct (merge with defaults)
                const currentValue = record.value || {};
                if (typeof currentValue.enabled !== 'boolean') {
                    await record.update({ value: { enabled: true } });
                    console.log(`[seed-auto-assignment] Updated value structure: ${config.key}`);
                } else {
                    console.log(`[seed-auto-assignment] Already exists: ${config.key} (enabled=${currentValue.enabled})`);
                }
            }
        }

        console.log('[seed-auto-assignment] Completed successfully.');
        process.exit(0);
    } catch (error) {
        console.error('[seed-auto-assignment] Error:', error);
        process.exit(1);
    }
}

seedAutoAssignmentConfigs();
