import { AuroraClient } from "@/lib/BotClient";
import { logger } from "@/lib/logger";

export async function actionsRoute(request: Request): Promise<Response> {
    const url = new URL(request.url);
    const body = await request.json().catch(() => ({})) as any;
    const action = body.action;

    if (!action) {
        return new Response(JSON.stringify({ success: false, error: "No action provided" }), {
            status: 400,
            headers: { "Content-Type": "application/json" }
        });
    }

    try {
        switch (action) {
            case "reload_commands":
                logger.info("Web Dashboard: Triggering command reload...");
                await AuroraClient.loadCommands(true);
                await AuroraClient.deployCommands();
                return new Response(JSON.stringify({ success: true, message: "Commands reloaded successfully" }), {
                    headers: { "Content-Type": "application/json" }
                });

            case "clear_cache":
                logger.info("Web Dashboard: Triggering cache clear...");
                // For now, we'll reload events and commands as a "clear cache" action
                await AuroraClient.loadEvents(true);
                await AuroraClient.loadCommands(true);
                return new Response(JSON.stringify({ success: true, message: "Cache cleared and systems reloaded" }), {
                    headers: { "Content-Type": "application/json" }
                });

            case "restart_bot":
                logger.info("Web Dashboard: Triggering bot restart...");
                // We don't await this because it will exit the process
                setTimeout(() => AuroraClient.shutdown(), 1000);
                return new Response(JSON.stringify({ success: true, message: "Bot shutdown initiated. If managed by a process manager, it will restart." }), {
                    headers: { "Content-Type": "application/json" }
                });

            default:
                return new Response(JSON.stringify({ success: false, error: `Unknown action: ${action}` }), {
                    status: 400,
                    headers: { "Content-Type": "application/json" }
                });
        }
    } catch (error: any) {
        logger.error(`Error executing action ${action}:`, error);
        return new Response(JSON.stringify({ success: false, error: error.message }), {
            status: 500,
            headers: { "Content-Type": "application/json" }
        });
    }
}
