/**
 * @fileoverview Guild settings endpoints for Aurora API.
 * Provides endpoints for reading and updating per-guild configuration
 * stored in the database.
 */

import type { RouteContext, RouteModule } from "./types";
import { jsonResponse, errorResponse, withErrorHandling } from "./utils";
import { guildSettingsService } from "@shared/modules/guild-settings/guild-settings.service";
import { invalidateGuildConfigCache } from "@shared/lib/config";

const GUILD_SETTINGS_PATTERN = /^\/api\/guilds\/(\d+)\/settings$/;

async function handler(ctx: RouteContext): Promise<Response | null> {
    const { pathname, method, req } = ctx;

    const match = pathname.match(GUILD_SETTINGS_PATTERN);
    if (!match || !match[1]) {
        return null;
    }

    const guildId = match[1];

    if (method === "GET") {
        return withErrorHandling(async () => {
            const settings = await guildSettingsService.getSettings(guildId);
            if (!settings) {
                return jsonResponse({ guildId, configured: false });
            }
            return jsonResponse({ ...settings, guildId, configured: true });
        }, "fetch guild settings");
    }

    if (method === "PUT" || method === "PATCH") {
        try {
            const body = await req.json() as Record<string, unknown>;
            const { guildId: _, ...settings } = body;
            const result = await guildSettingsService.upsertSettings({
                guildId,
                ...settings,
            } as Parameters<typeof guildSettingsService.upsertSettings>[0]);
            invalidateGuildConfigCache(guildId);
            return jsonResponse(result);
        } catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            return errorResponse("Failed to save guild settings", 400, message);
        }
    }

    if (method === "DELETE") {
        return withErrorHandling(async () => {
            await guildSettingsService.deleteSettings(guildId);
            invalidateGuildConfigCache(guildId);
            return jsonResponse({ success: true });
        }, "delete guild settings");
    }

    return null;
}

export const guildSettingsRoutes: RouteModule = {
    name: "guild-settings",
    handler
};
