import { adminForbidden, isAdminRequest } from "../../../lib/admin-auth";
import { ensureSchema, getRawDb, getUploadBucket } from "../../../lib/mvp-db";
import { parseResultScreenshotKeys } from "../../../lib/result-screenshots";

export async function GET(request: Request) {
  if (!(await isAdminRequest(request))) return adminForbidden();
  try {
    await ensureSchema();
    const distributionId = new URL(request.url).searchParams
      .get("distribution")
      ?.trim();
    const imageIndex = Math.max(
      1,
      Number(new URL(request.url).searchParams.get("index") || 1),
    );
    if (!distributionId) {
      return Response.json({ error: "缺少任务记录" }, { status: 400 });
    }
    const row = await getRawDb()
      .prepare(
        `SELECT result_screenshot_key FROM distributions
         WHERE id = ?`,
      )
      .bind(distributionId)
      .first<{ result_screenshot_key: string | null }>();
    const screenshotKey = row
      ? parseResultScreenshotKeys(row.result_screenshot_key)[imageIndex - 1]
      : undefined;
    if (!screenshotKey) {
      return Response.json({ error: "任务截图不存在" }, { status: 404 });
    }
    const object = await getUploadBucket().get(screenshotKey);
    if (!object) {
      return Response.json({ error: "任务截图不存在" }, { status: 404 });
    }
    const headers = new Headers({
      "Cache-Control": "private, no-store",
      "Content-Disposition": 'inline; filename="task-result-screenshot"',
      "X-Content-Type-Options": "nosniff",
    });
    object.writeHttpMetadata(headers);
    return new Response(await object.arrayBuffer(), { headers });
  } catch (error) {
    return Response.json(
      { error: error instanceof Error ? error.message : "截图读取失败" },
      { status: 500 },
    );
  }
}
