import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { uploadObject, BUCKETS } from "@/lib/storage";

export async function POST(request: Request) {
  try {
    // Validate session — irrigators use wl_session, admins use wl_admin_session
    const cookieStore = await cookies();
    const sessionId = cookieStore.get("wl_session")?.value ?? cookieStore.get("wl_admin_session")?.value;
    if (!sessionId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const formData = await request.formData();
    const file = formData.get("file") as File | null;
    const bucket = formData.get("bucket") as string | null;

    if (!file) {
      return NextResponse.json({ error: "Missing file" }, { status: 400 });
    }

    if (file.size > 5 * 1024 * 1024) {
      return NextResponse.json({ error: "File too large (max 5MB)" }, { status: 400 });
    }

    if (!["image/jpeg", "image/png"].includes(file.type)) {
      return NextResponse.json({ error: "Only JPG or PNG allowed" }, { status: 400 });
    }

    const ext = file.type === "image/jpeg" ? "jpg" : "png";
    const key = `water-logs/${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;

    // bucket param is accepted for backwards compat but ignored — always use WATER_LOGS
    const buffer = Buffer.from(await file.arrayBuffer());
    const url = await uploadObject({
      bucket: BUCKETS.WATER_LOGS,
      key,
      body: buffer,
      contentType: file.type,
    });

    return NextResponse.json({ url });
  } catch (err) {
    return NextResponse.json({ error: "Server error" }, { status: 500 });
  }
}