import { logError } from "@/lib/logger";
import type { TDashboardStorage } from "@/lib/storage/dashboard-storage";
import { Readable } from "node:stream";
import { safeRelativePath } from "./dashboard-bundle.validator";

export const DASHBOARD_CSP = [
  "default-src 'none'",
  "script-src 'unsafe-inline' 'self'",
  "style-src 'unsafe-inline' 'self'",
  "img-src 'self' data:",
  "font-src 'self' data:",
  "connect-src 'none'",
  "form-action 'none'",
  "base-uri 'none'",
  "frame-ancestors 'self'",
].join("; ");

export const applyServeHeaders = (headers: Headers) => {
  headers.set("Content-Security-Policy", DASHBOARD_CSP);
  headers.set("X-Content-Type-Options", "nosniff");
  headers.set("X-Frame-Options", "SAMEORIGIN");
  headers.set("Cache-Control", "private, no-store");
  headers.set("Referrer-Policy", "no-referrer");
};

export type ServeVersion = {
  id: string;
  storage_prefix: string;
  entry_point: string;
};

export type ServeViewer = {
  consoleUserId: string | null;
  publicLinkId: string | null;
};

export type ServeOutcome =
  | { ok: true; response: Response; servedEntryPoint: boolean }
  | { ok: false; status: 400 | 404; message: string };

export type ServeAssetParams = {
  storage: TDashboardStorage;
  dashboardId: string;
  version: ServeVersion;
  requestedPath: string;
  viewer: ServeViewer;
  ipAddress: string | null;
  recordView: (entry: {
    dashboardId: string;
    versionId: string;
    consoleUserId: string | null;
    publicLinkId: string | null;
    ipAddress: string | null;
  }) => Promise<void>;
  onEntryPointServed?: () => Promise<void>;
};

export const serveDashboardAsset = async ({
  storage,
  dashboardId,
  version,
  requestedPath,
  viewer,
  ipAddress,
  recordView,
  onEntryPointServed,
}: ServeAssetParams): Promise<ServeOutcome> => {
  const isBareServe = requestedPath === "";
  const wanted = isBareServe ? version.entry_point : requestedPath;

  const safePath = safeRelativePath(wanted);
  if (safePath === null) {
    return { ok: false, status: 400, message: "Invalid asset path." };
  }

  const fullPath = `${version.storage_prefix}/${safePath}`;
  const object = await storage.getObject(fullPath);
  if (!object) {
    return { ok: false, status: 404, message: "Asset not found." };
  }

  const servedEntryPoint = isBareServe || safePath === version.entry_point;
  if (servedEntryPoint) {
    try {
      await recordView({
        dashboardId,
        versionId: version.id,
        consoleUserId: viewer.consoleUserId,
        publicLinkId: viewer.publicLinkId,
        ipAddress,
      });
    } catch (err) {
      logError(err, "Failed recording dashboard view");
    }
    if (onEntryPointServed) {
      try {
        await onEntryPointServed();
      } catch (err) {
        logError(err, "Failed post-serve bookkeeping for dashboard view");
      }
    }
  }

  const headers = new Headers();
  headers.set("Content-Type", object.contentType);
  if (object.size > 0) headers.set("Content-Length", String(object.size));
  applyServeHeaders(headers);

  return {
    ok: true,
    servedEntryPoint,
    response: new Response(
      Readable.toWeb(object.stream) as unknown as ReadableStream,
      { status: 200, headers },
    ),
  };
};

export const relativePathFromServeUrl = (
  requestPath: string,
  marker: string,
): string | null => {
  const at = requestPath.indexOf(marker);
  if (at === -1) return "";
  let rest = requestPath.slice(at + marker.length);
  if (rest.startsWith("/")) rest = rest.slice(1);
  if (rest === "") return "";
  try {
    return decodeURIComponent(rest);
  } catch {
    return null;
  }
};
