import { env } from "cloudflare:workers";
import { getChatGPTUser } from "../../../../chatgpt-auth";

export const dynamic = "force-dynamic";

export async function GET(_: Request, context: { params: Promise<{ id: string; path: string[] }> }) {
  const user = await getChatGPTUser() ?? { email: "prototype@connectpoint.net" };
  const { id, path } = await context.params;
  const item = await env.DB.prepare(
    "SELECT owner_email AS ownerEmail,package_key AS packageKey FROM training_content WHERE id=?"
  ).bind(Number(id)).first<{ ownerEmail: string; packageKey: string | null }>();
  if (!item?.packageKey) return new Response(null, { status: 404 });
  const base = item.packageKey.replace(/source\.zip$/, "files/");
  const cleanPath = path.join("/").replace(/\.\./g, "");
  const object = await env.EVIDENCE_BUCKET.get(base + cleanPath);
  if (!object) return new Response(null, { status: 404 });
  const headers = new Headers();
  object.writeHttpMetadata(headers);
  headers.set("cache-control", "private, max-age=300");
  headers.set("x-content-type-options", "nosniff");
  if ((headers.get("content-type") ?? "").startsWith("text/html")) {
    let html = await object.text();
    const baseTag = `<base href="/api/scorm/${id}/${cleanPath.includes("/") ? cleanPath.slice(0, cleanPath.lastIndexOf("/") + 1) : ""}">`;
    html = /<head[^>]*>/i.test(html) ? html.replace(/<head([^>]*)>/i, `<head$1>${baseTag}`) : baseTag + html;
    return new Response(html, { headers });
  }
  headers.set("x-connectpoint-learner", user.email);
  return new Response(object.body, { headers });
}
