import {
  ensureSchema,
  getRawDb,
  getUploadBucket,
} from "../../../lib/mvp-db";
import { adminForbidden, isAdminRequest } from "../../../lib/admin-auth";
import { verifyCreatorScreenshotAccessToken } from "../../../lib/creator-screenshot-access";

export async function GET(request: Request) {
  const isAdmin = await isAdminRequest(request);
  try {
    await ensureSchema();
    const distributionId = new URL(request.url).searchParams
      .get("distribution")
      ?.trim();
    if (!distributionId) {
      return Response.json({ error: "缺少分发记录" }, { status: 400 });
    }
    const row = await getRawDb()
      .prepare(
        `SELECT screenshot_key FROM distributions
         WHERE id = ?`,
      )
      .bind(distributionId)
      .first<{ screenshot_key: string | null }>();
    const mcpToken = new URL(request.url).searchParams.get("mcp_token") || "";
    if (
      !isAdmin &&
      (!row?.screenshot_key ||
        !verifyCreatorScreenshotAccessToken(
          distributionId,
          row.screenshot_key,
          mcpToken,
        ))
    ) {
      return adminForbidden();
    }
    if (
      !row?.screenshot_key ||
      !row.screenshot_key.startsWith("creator-center/")
    ) {
      return Response.json({ error: "创作者截图不存在" }, { status: 404 });
    }
    const object = await getUploadBucket().get(row.screenshot_key);
    if (!object) {
      return Response.json({ error: "创作者截图不存在" }, { status: 404 });
    }
    const headers = new Headers({
      "Cache-Control": "private, no-store",
      "Content-Disposition": 'inline; filename="creator-center-screenshot"',
      "X-Content-Type-Options": "nosniff",
    });
    object.writeHttpMetadata(headers);
    if (!headers.get("Content-Type")) {
      headers.set("Content-Type", "image/jpeg");
    }
    return new Response(await object.arrayBuffer(), { headers });
  } catch (error) {
    return Response.json(
      { error: error instanceof Error ? error.message : "截图读取失败" },
      { status: 500 },
    );
  }
}
