import { env } from "cloudflare:workers";
import { getAppIdentity, forbidden, unauthorised } from "../../api-auth";

export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  const user = await getAppIdentity();
  if (!user) return unauthorised();
  const state = await env.DB.prepare(
    "SELECT organisation_logo_key AS logoKey, organisation_logo_name AS logoName FROM learner_state WHERE email=?"
  ).bind(user.email).first<{ logoKey: string | null; logoName: string | null }>();
  if (new URL(request.url).searchParams.get("image") === "1") {
    if (!state?.logoKey) return new Response(null, { status: 404 });
    const object = await env.EVIDENCE_BUCKET.get(state.logoKey);
    if (!object) return new Response(null, { status: 404 });
    const headers = new Headers();
    object.writeHttpMetadata(headers);
    headers.set("cache-control", "private, max-age=300");
    return new Response(object.body, { headers });
  }
  return Response.json({ logoName: state?.logoName ?? null, logoUrl: state?.logoKey ? "/api/branding?image=1" : null });
}

export async function POST(request: Request) {
  const user = await getAppIdentity();
  if (!user) return unauthorised();
  if (user.role !== "admin") return forbidden();
  const form = await request.formData();
  const logo = form.get("logo");
  if (!(logo instanceof File) || logo.size === 0) {
    return Response.json({ error: "Choose a logo image." }, { status: 400 });
  }
  if (logo.size > 5 * 1024 * 1024) return Response.json({ error: "Logo images must be under 5 MB." }, { status: 400 });
  if (!["image/png", "image/jpeg", "image/webp"].includes(logo.type)) {
    return Response.json({ error: "Upload a PNG, JPG or WebP logo." }, { status: 400 });
  }
  const key = `organisation-branding/${user.email}/${crypto.randomUUID()}-${logo.name.replace(/[^a-z0-9._-]/gi, "_")}`;
  await env.EVIDENCE_BUCKET.put(key, logo.stream(), {
    httpMetadata: { contentType: logo.type },
    customMetadata: { owner: user.email, purpose: "organisation-logo" },
  });
  const previous = await env.DB.prepare("SELECT organisation_logo_key AS logoKey FROM learner_state WHERE email=?")
    .bind(user.email).first<{ logoKey: string | null }>();
  await env.DB.prepare(
    "UPDATE learner_state SET organisation_logo_key=?, organisation_logo_name=?, updated_at=? WHERE email=?"
  ).bind(key, logo.name, new Date().toISOString(), user.email).run();
  if (previous?.logoKey) await env.EVIDENCE_BUCKET.delete(previous.logoKey);
  return GET(request);
}
