import { createFileRoute } from "@tanstack/react-router";
import { logger } from "@/lib/logger";

export const Route = createFileRoute(
  "/api/files/$collection/$recordId/$file"
)({
  server: {
    handlers: {
      GET: async ({ params, request }) => {
        try {
          const { collection, recordId, file } = params;
          const pocketbaseUrl =
            process.env.POCKETBASE_URL || "http://127.0.0.1:8090";
          const fileUrl = `${pocketbaseUrl}/api/files/${collection}/${recordId}/${file}`;

          const response = await fetch(fileUrl, {
            method: "GET",
            headers: {
              ...(request.headers.get("range") && {
                Range: request.headers.get("range")!,
              }),
              ...(request.headers.get("if-none-match") && {
                "If-None-Match": request.headers.get("if-none-match")!,
              }),
              ...(request.headers.get("if-modified-since") && {
                "If-Modified-Since": request.headers.get("if-modified-since")!,
              }),
            },
          });

          if (!response.ok) {
            logger.error("PocketBase file request failed", {
              status: response.status,
              statusText: response.statusText,
              url: fileUrl,
            });

            if (response.status === 404) {
              return new Response("File not found", { status: 404 });
            }

            return new Response(`PocketBase error: ${response.statusText}`, {
              status: response.status,
            });
          }

          const body = response.body;
          const responseHeaders = new Headers();
          const headers = [
            "content-type",
            "content-length",
            "content-disposition",
            "etag",
            "last-modified",
            "cache-control",
            "accept-ranges",
            "content-range",
          ];

          headers.forEach((header) => {
            const value = response.headers.get(header);
            if (value) {
              responseHeaders.set(header, value);
            }
          });

          responseHeaders.set("Access-Control-Allow-Origin", "*");
          responseHeaders.set(
            "Access-Control-Allow-Methods",
            "GET, HEAD, OPTIONS"
          );
          responseHeaders.set(
            "Access-Control-Allow-Headers",
            "Range, If-None-Match, If-Modified-Since"
          );

          return new Response(body, {
            status: response.status,
            statusText: response.statusText,
            headers: responseHeaders,
          });
        } catch (error) {
          logger.error("File proxy error", error);
          return new Response("Internal server error", { status: 500 });
        }
      },

      OPTIONS: () => {
        return new Response(null, {
          status: 200,
          headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET, OPTIONS",
            "Access-Control-Max-Age": "86400",
          },
        });
      },
    },
  },
});
