/**
 * @fileoverview Bot settings endpoints for Aurora API.
 * Provides endpoints for reading and updating bot configuration,
 * as well as fetching Discord metadata.
 */

import type { RouteContext, RouteModule } from "./types";
import { jsonResponse, errorResponse, withErrorHandling } from "./utils";

/**
 * Settings routes handler.
 * 
 * Endpoints:
 * - GET /api/settings - Get current bot configuration
 * - POST /api/settings - Update bot configuration (partial merge)
 * - GET /api/settings/meta - Get Discord metadata (roles, channels, commands)
 */
async function handler(ctx: RouteContext): Promise<Response | null> {
    const { pathname, method, req } = ctx;

    // Only handle requests to /api/settings*
    if (!pathname.startsWith("/api/settings")) {
        return null;
    }

    /**
     * @route GET /api/settings
     * @description Returns the current bot configuration from database.
     * Configuration includes economy settings, leveling settings,
     * command toggles, and other system settings.
     * @response 200 - Full configuration object (DB format with strings for BigInts)
     * @response 500 - Error fetching settings
     * 
     * @example
     * // Response
     * {
     *   "economy": { "daily": { "amount": "100", "streakBonus": "10" } },
     *   "leveling": { "base": 100, "exponent": 1.5 },
     *   "commands": { "disabled": [], "channelLocks": {} }
     * }
     */
    if (pathname === "/api/settings" && method === "GET") {
        return withErrorHandling(async () => {
            const { gameSettingsService } = await import("@shared/modules/game-settings/game-settings.service");
            const settings = await gameSettingsService.getSettings();
            
            if (!settings) {
                // Return defaults if no settings in DB yet
                return jsonResponse(gameSettingsService.getDefaults());
            }
            
            return jsonResponse(settings);
        }, "fetch settings");
    }

    /**
     * @route POST /api/settings
     * @description Updates bot configuration with partial merge.
     * Only the provided fields will be updated; other settings remain unchanged.
     * After updating, commands are automatically reloaded.
     * 
     * @body Partial configuration object (DB format with strings for BigInts)
     * @response 200 - `{ success: true }`
     * @response 400 - Validation error
     * @response 500 - Error saving settings
     * 
     * @example
     * // Request - Only update economy daily reward
     * POST /api/settings
     * { "economy": { "daily": { "amount": "150" } } }
     */
    if (pathname === "/api/settings" && method === "POST") {
        try {
            const partialConfig = await req.json() as Record<string, unknown>;
            const { gameSettingsService } = await import("@shared/modules/game-settings/game-settings.service");
            
            // Use upsertSettings to merge partial update
            await gameSettingsService.upsertSettings(partialConfig as Record<string, unknown>);

            const { systemEvents, EVENTS } = await import("@shared/lib/events");
            systemEvents.emit(EVENTS.ACTIONS.RELOAD_COMMANDS);

            return jsonResponse({ success: true });
        } catch (error) {
            // Return 400 for validation errors
            const message = error instanceof Error ? error.message : String(error);
            return errorResponse("Failed to save settings", 400, message);
        }
    }

    /**
     * @route GET /api/settings/meta
     * @description Returns Discord server metadata for settings UI.
     * Provides lists of roles, channels, and registered commands.
     * 
     * @response 200 - `{ roles: Role[], channels: Channel[], commands: Command[] }`
     * @response 500 - Error fetching metadata
     * 
     * @example
     * // Response
     * {
     *   "roles": [
     *     { "id": "123456789", "name": "Admin", "color": "#FF0000" }
     *   ],
     *   "channels": [
     *     { "id": "987654321", "name": "general", "type": 0 }
     *   ],
     *   "commands": [
     *     { "name": "daily", "category": "economy" }
     *   ]
     * }
     */
    if (pathname === "/api/settings/meta" && method === "GET") {
        return withErrorHandling(async () => {
            const { AuroraClient } = await import("../../../bot/lib/BotClient");
            const { env } = await import("@shared/lib/env");

            if (!env.DISCORD_GUILD_ID) {
                return jsonResponse({ roles: [], channels: [], commands: [] });
            }

            const guild = AuroraClient.guilds.cache.get(env.DISCORD_GUILD_ID);
            if (!guild) {
                return jsonResponse({ roles: [], channels: [], commands: [] });
            }

            // Map roles and channels to a simplified format
            const roles = guild.roles.cache
                .sort((a, b) => b.position - a.position)
                .map(r => ({ id: r.id, name: r.name, color: r.hexColor }));

            const channels = guild.channels.cache
                .map(c => ({ id: c.id, name: c.name, type: c.type }));

            const commands = Array.from(AuroraClient.knownCommands.entries())
                .map(([name, category]) => ({ name, category }))
                .sort((a, b) => {
                    if (a.category !== b.category) return a.category.localeCompare(b.category);
                    return a.name.localeCompare(b.name);
                });

            return jsonResponse({ guildId: env.DISCORD_GUILD_ID, roles, channels, commands });
        }, "fetch settings meta");
    }

    return null;
}

export const settingsRoutes: RouteModule = {
    name: "settings",
    handler
};
