import { openStore } from "@/lib/data/store";

export type ImageVerdict = { allowed: boolean; reason?: string; flagged: boolean };

/**
 * Checks a photo for adult content using Google Vision, when configured.
 *
 * Fails open: if the service is unreachable or no key is set, the upload
 * goes through. A moderation service being down shouldn't stop the site
 * working, and everything still passes through reports afterwards.
 */
export async function checkImage(bytes: Buffer, mime: string): Promise<ImageVerdict> {
  if (!mime.startsWith("image/")) return { allowed: true, flagged: false };

  const store = await openStore();
  const s = await store.settings();
  if (s.adultImagesEnabled !== true) return { allowed: true, flagged: false };

  const key = String(s.adultImagesApiKey ?? "").trim();
  if (!key) return { allowed: true, flagged: false };

  try {
    const res = await fetch(
      `https://vision.googleapis.com/v1/images:annotate?key=${encodeURIComponent(key)}`,
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          requests: [
            {
              image: { content: bytes.toString("base64") },
              features: [{ type: "SAFE_SEARCH_DETECTION" }],
            },
          ],
        }),
      }
    );

    if (!res.ok) return { allowed: true, flagged: false };

    const data = await res.json();
    const safe = data?.responses?.[0]?.safeSearchAnnotation;
    if (!safe) return { allowed: true, flagged: false };

    const serious = ["LIKELY", "VERY_LIKELY"];
    const flagged =
      serious.includes(safe.adult) ||
      serious.includes(safe.racy) ||
      serious.includes(safe.violence);

    if (!flagged) return { allowed: true, flagged: false };

    // What happens to a flagged image is the admin's choice.
    const action = String(s.adultImagesAction ?? "Refuse the upload");
    if (action === "Refuse the upload") {
      return {
        allowed: false,
        flagged: true,
        reason: "That image was flagged as unsuitable",
      };
    }
    // "Hold for review" and "Allow but mark it" both let it through; the
    // flag is what the caller acts on.
    return { allowed: true, flagged: true };
  } catch {
    return { allowed: true, flagged: false };
  }
}
