import { gameSettingsService } from "@shared/modules/game-settings/game-settings.service";
import { readFileSync, existsSync } from "node:fs";
import { join } from "node:path";

const configPath = join(import.meta.dir, '..', 'config', 'config.json');

interface FileConfig {
    leveling: {
        base: number;
        exponent: number;
        chat: {
            cooldownMs: number;
            minXp: number;
            maxXp: number;
        };
    };
    economy: {
        daily: {
            amount: string | number;
            streakBonus: string | number;
            weeklyBonus: string | number;
            cooldownMs: number;
        };
        transfers: {
            allowSelfTransfer: boolean;
            minAmount: string | number;
        };
        exam: {
            multMin: number;
            multMax: number;
        };
    };
    inventory: {
        maxStackSize: string | number;
        maxSlots: number;
    };
    lootdrop: {
        activityWindowMs: number;
        minMessages: number;
        spawnChance: number;
        cooldownMs: number;
        reward: {
            min: number;
            max: number;
            currency: string;
        };
    };
    trivia: {
        entryFee: string | number;
        rewardMultiplier: number;
        timeoutSeconds: number;
        cooldownMs: number;
        categories: number[];
        difficulty: 'easy' | 'medium' | 'hard' | 'random';
    };
    moderation: {
        prune: {
            maxAmount: number;
            confirmThreshold: number;
            batchSize: number;
            batchDelayMs: number;
        };
    };
    commands: Record<string, boolean>;
    system: Record<string, unknown>;
}

async function migrateGameSettingsToDatabase() {
    console.log("🎮 Migrating game settings to database...\n");

    const existing = await gameSettingsService.getSettings(false);
    if (existing) {
        console.log("Game settings already exist in database:");
        console.log(JSON.stringify(existing, null, 2));
        console.log("\nSkipping migration. Delete existing settings first if you want to re-migrate.");
        return;
    }

    if (!existsSync(configPath)) {
        console.log("No config.json file found. Creating default settings...");
        await gameSettingsService.upsertSettings(gameSettingsService.getDefaults());
        console.log("✅ Default game settings created in database.");
        return;
    }

    const raw = readFileSync(configPath, 'utf-8');
    const fileConfig: FileConfig = JSON.parse(raw);

    await gameSettingsService.upsertSettings({
        leveling: fileConfig.leveling,
        economy: {
            daily: {
                amount: String(fileConfig.economy.daily.amount),
                streakBonus: String(fileConfig.economy.daily.streakBonus),
                weeklyBonus: String(fileConfig.economy.daily.weeklyBonus ?? 50),
                cooldownMs: fileConfig.economy.daily.cooldownMs,
            },
            transfers: {
                allowSelfTransfer: fileConfig.economy.transfers.allowSelfTransfer,
                minAmount: String(fileConfig.economy.transfers.minAmount),
            },
            exam: fileConfig.economy.exam,
        },
        inventory: {
            maxStackSize: String(fileConfig.inventory.maxStackSize),
            maxSlots: fileConfig.inventory.maxSlots,
        },
        lootdrop: fileConfig.lootdrop,
        trivia: {
            ...fileConfig.trivia,
            entryFee: String(fileConfig.trivia.entryFee),
        },
        moderation: fileConfig.moderation,
        commands: fileConfig.commands ?? {},
        system: fileConfig.system ?? {},
    });

    console.log("✅ Game settings migrated to database!");
    console.log("\nGame-wide settings are now stored in the database.");
    console.log("The config.json file can be safely deleted after verification.");
}

migrateGameSettingsToDatabase()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error("Migration failed:", error);
        process.exit(1);
    });
