import { NextRequest, NextResponse } from "next/server";
import { randomUUID } from "node:crypto";
import sharp from "sharp";
import { revalidatePath } from "next/cache";
import { isLocalAdmin } from "@/lib/admin-auth";
import { createClient, isSupabaseConfigured } from "@/lib/supabase/server";
import { changePhoto, listPhotos, storePhoto } from "@/lib/gallery-store";
export const runtime="nodejs";
async function allowed(){if(await isLocalAdmin())return true;if(!isSupabaseConfigured())return false;const db=await createClient();const {data:{user}}=await db.auth.getUser();if(!user)return false;const {data}=await db.from("admin_users").select("user_id").eq("user_id",user.id).maybeSingle();return Boolean(data);}
export async function GET(){if(!await allowed())return NextResponse.json({error:"Please sign in."},{status:401});return NextResponse.json({photos:await listPhotos()},{headers:{"Cache-Control":"no-store"}});}
export async function POST(req:NextRequest){
  if(!await allowed())return NextResponse.json({error:"Please sign in."},{status:401});
  const origin=req.headers.get("origin");
  let sameOrigin=false;
  try {const parsed=new URL(origin||"");sameOrigin=["http:","https:"].includes(parsed.protocol)&&parsed.host===req.headers.get("host");}catch{}
  if(!sameOrigin)return NextResponse.json({error:"Invalid request origin."},{status:403});
  if(Number(req.headers.get("content-length"))>9_000_000)return NextResponse.json({error:"Choose a photo smaller than 8 MB."},{status:413});
  try {
    const form=await req.formData();const id=String(form.get("id")||"");const rows=await listPhotos();const old=rows.find(p=>p.id===id);
    if(id&&!old)return NextResponse.json({error:"Photo not found. Refresh and try again."},{status:404});
    if(form.get("action")==="remove") {if(!old)return NextResponse.json({error:"Photo not found."},{status:404});await changePhoto(old,true);}
    else {
      const alt=String(form.get("alt")||"").trim();const category=String(form.get("category")||"").trim();const order=Number(form.get("order")||0);
      if(!alt||alt.length>250||!category||category.length>60||!Number.isInteger(order)||order<0||order>9999)return NextResponse.json({error:"Add a description, category, and a valid display order."},{status:400});
      let src=old?.src;const file=form.get("image");
      if(file instanceof File&&file.size){
        if(file.size>8_000_000||!["image/jpeg","image/png","image/webp","image/avif"].includes(file.type))return NextResponse.json({error:"Upload a JPG, PNG, WebP, or AVIF photo under 8 MB."},{status:400});
        let bytes:Buffer;
        try {bytes=await sharp(Buffer.from(await file.arrayBuffer()),{limitInputPixels:40_000_000}).rotate().resize({width:2000,height:2000,fit:"inside",withoutEnlargement:true}).webp({quality:88}).toBuffer();}
        catch{return NextResponse.json({error:"That image could not be read. Try a JPG or PNG export."},{status:400});}
        src=await storePhoto(bytes);
      }
      if(!src)return NextResponse.json({error:"Choose a photo to upload."},{status:400});
      await changePhoto({id:old?.id||randomUUID(),src,alt,category,order,published:form.get("published")==="on"});
    }
    revalidatePath("/gallery");revalidatePath("/");revalidatePath("/admin/local");
    return NextResponse.json({ok:true});
  }catch{return NextResponse.json({error:"Your changes could not be saved. Please try again."},{status:500});}
}
