import { env } from "cloudflare:workers";

import { getChatGPTUser } from "@/app/chatgpt-auth";

export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  const user = await getChatGPTUser();
  if (!user) return Response.json({ error: "请先登录" }, { status: 401 });
  const key = new URL(request.url).searchParams.get("key") ?? "";
  if (!key.startsWith("projects/") || key.includes("..")) return Response.json({ error: "文件路径无效" }, { status: 400 });
  const projectId = key.split("/")[1] ?? "";
  const role = await env.DB.prepare("SELECT role FROM workspace_users WHERE email = ?").bind(user.email).first<{ role: string }>();
  if (!role || !["owner", "operator", "reviewer"].includes(role.role)) {
    const membership = await env.DB.prepare(
      `SELECT m.id FROM geo_project_members m JOIN geo_projects p ON p.id = m.project_id
      WHERE m.project_id = ? AND m.user_email = ? AND m.status = 'active' AND p.status <> 'recycle_bin'`,
    ).bind(projectId, user.email).first();
    if (!membership) return Response.json({ error: "无权查看该项目文件" }, { status: 403 });
  }
  const object = await env.BUCKET.get(key);
  if (!object) return Response.json({ error: "文件不存在" }, { status: 404 });
  const headers = new Headers({
    "cache-control": "private, max-age=300",
    etag: object.httpEtag,
    "x-content-type-options": "nosniff",
  });
  object.writeHttpMetadata(headers);
  const contentType = object.httpMetadata?.contentType ?? "application/octet-stream";
  if (!/^image\/(png|jpeg|webp)$/i.test(contentType)) {
    headers.set("content-disposition", "attachment");
    headers.set("content-security-policy", "sandbox; default-src 'none'");
  }
  return new Response(object.body, { headers });
}
