/**
 * @fileoverview Static asset serving for Aurora API.
 * Serves item images and other assets from the local filesystem.
 */

import { join, resolve, dirname } from "path";
import type { RouteContext, RouteModule } from "./types";

// Resolve assets root directory
const currentDir = dirname(new URL(import.meta.url).pathname);
const assetsRoot = resolve(currentDir, "../../../bot/assets/graphics");

/** MIME types for supported image formats */
const MIME_TYPES: Record<string, string> = {
    "png": "image/png",
    "jpg": "image/jpeg",
    "jpeg": "image/jpeg",
    "webp": "image/webp",
    "gif": "image/gif",
};

/**
 * Assets routes handler.
 * 
 * Endpoints:
 * - GET /assets/* - Serve static files from the assets directory
 */
async function handler(ctx: RouteContext): Promise<Response | null> {
    const { pathname, method } = ctx;

    /**
     * @route GET /assets/*
     * @description Serves static asset files (images) with caching headers.
     * Assets are served from the bot's graphics directory.
     * 
     * Path security: Path traversal attacks are prevented by validating
     * that the resolved path stays within the assets root.
     * 
     * @response 200 - File content with appropriate MIME type
     * @response 403 - Forbidden (path traversal attempt)
     * @response 404 - File not found
     * 
     * @example
     * // Request
     * GET /assets/items/1.png
     * 
     * // Response Headers
     * Content-Type: image/png
     * Cache-Control: public, max-age=86400
     */
    if (pathname.startsWith("/assets/") && method === "GET") {
        const assetPath = pathname.replace("/assets/", "");

        // Security: prevent path traversal attacks
        const safePath = join(assetsRoot, assetPath);
        if (!safePath.startsWith(assetsRoot)) {
            return new Response("Forbidden", { status: 403 });
        }

        const file = Bun.file(safePath);
        if (await file.exists()) {
            // Determine MIME type based on extension
            const ext = safePath.split(".").pop()?.toLowerCase();
            const contentType = MIME_TYPES[ext || ""] || "application/octet-stream";

            return new Response(file, {
                headers: {
                    "Content-Type": contentType,
                    "Cache-Control": "no-cache",
                }
            });
        }

        return new Response("Not found", { status: 404 });
    }

    return null;
}

export const assetsRoutes: RouteModule = {
    name: "assets",
    handler
};
