import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { isCsrfSafe, csrfForbiddenPayload } from "@/lib/csrf";

// Bucket → akses public/private
const BUCKET_VISIBILITY: Record<string, "public" | "private"> = {
  "reference-images": "private",
  "product-images":   "private",
  "avatars":          "public",
};

export async function POST(request: NextRequest) {
  // BUG-13 FIX: CSRF check
  if (!isCsrfSafe(request)) {
    return NextResponse.json(csrfForbiddenPayload(), { status: 403 });
  }

  const supabase = createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const formData = await request.formData();
  const file     = formData.get("file") as File;
  const bucket   = (formData.get("bucket") as string) ?? "reference-images";

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

  // Validasi bucket
  if (!Object.keys(BUCKET_VISIBILITY).includes(bucket)) {
    return NextResponse.json({ error: "Invalid bucket" }, { status: 400 });
  }

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

  const allowedTypes = ["image/jpeg", "image/png", "image/webp", "image/gif"];
  if (!allowedTypes.includes(file.type)) {
    return NextResponse.json({ error: "Invalid file type. Allowed: JPEG, PNG, WebP, GIF" }, { status: 400 });
  }

  // Paksa ekstensi dari MIME type (jangan percaya file.name)
  const extMap: Record<string, string> = {
    "image/jpeg": "jpg",
    "image/png":  "png",
    "image/webp": "webp",
    "image/gif":  "gif",
  };
  const ext      = extMap[file.type];
  const filename = `${user.id}/${Date.now()}.${ext}`;

  const { data, error } = await supabase.storage
    .from(bucket)
    .upload(filename, file, { contentType: file.type, upsert: false });

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

  // ── URL strategy berdasarkan visibilitas bucket ──────────────────────────
  // Private bucket: kembalikan path saja, client generate signed URL saat dibutuhkan.
  // Public bucket: gunakan public URL langsung.
  if (BUCKET_VISIBILITY[bucket] === "private") {
    // Buat signed URL dengan TTL 1 jam sebagai preview langsung
    const { data: signed, error: signErr } = await supabase.storage
      .from(bucket)
      .createSignedUrl(data.path, 60 * 60); // 1 jam

    if (signErr || !signed) {
      // Fallback: kembalikan path saja, FE akan request signed URL via API lain
      return NextResponse.json({ path: data.path, bucket, url: null });
    }

    return NextResponse.json({ url: signed.signedUrl, path: data.path, bucket });
  }

  // Public bucket (avatars)
  const { data: { publicUrl } } = supabase.storage.from(bucket).getPublicUrl(data.path);
  return NextResponse.json({ url: publicUrl, path: data.path, bucket });
}
