import { BaseSchema } from '@adonisjs/lucid/schema';

/**
 * Migration: Seed default AI settings
 * Inserts default DeepSeek AI configuration into scammer_settings table.
 * Uses INSERT OR IGNORE to avoid overwriting user-configured settings.
 */
export default class extends BaseSchema {
    tableName = 'scammer_settings';

    async up() {
        const now = new Date().toISOString();

        const defaults = [
            { key: 'ai_enabled',                  value: '0' },
            { key: 'ai_api_key',                   value: '' },
            { key: 'ai_auto_reply_enabled',        value: '0' },
            { key: 'ai_auto_reply_prefix',         value: '' },
            { key: 'ai_auto_reply_system_prompt',  value: '' },
            { key: 'ai_greeting_enabled',          value: '0' },
            { key: 'ai_greeting_prompt',           value: '' },
            { key: 'ai_scam_detect_enabled',       value: '0' },
            { key: 'ai_scam_detect_threshold',     value: '80' },
            { key: 'ai_scam_action',               value: 'warn' },
        ];

        for (const setting of defaults) {
            // Only insert if key does not exist yet (preserve user changes)
            const existing = await this.db.from('scammer_settings').where('key', setting.key).first();
            if (!existing) {
                await this.db.table('scammer_settings').insert({
                    key: setting.key,
                    value: setting.value,
                    created_at: now,
                    updated_at: now,
                });
            }
        }
    }

    async down() {
        const aiKeys = [
            'ai_enabled', 'ai_api_key', 'ai_auto_reply_enabled',
            'ai_auto_reply_prefix', 'ai_auto_reply_system_prompt',
            'ai_greeting_enabled', 'ai_greeting_prompt',
            'ai_scam_detect_enabled', 'ai_scam_detect_threshold', 'ai_scam_action',
        ];
        await this.db.from('scammer_settings').whereIn('key', aiKeys).delete();
    }
}
