import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { createAdminClient } from "@/lib/supabase/admin";

export const dynamic = "force-dynamic";
export const maxDuration = 60;

const BUCKET_CONFIGS: Record<
  string,
  { maxSize: number; allowedMimes: string[]; allowedExtensions: string[] }
> = {
  "property-images": {
    maxSize: 15 * 1024 * 1024, // 15MB
    allowedMimes: [
      "image/jpeg",
      "image/png",
      "image/webp",
      "image/avif",
      "image/gif",
      "image/jpg",
      "image/pjpeg",
      "image/jfif",
      "image/heic",
      "image/heif",
      "image/bmp",
      "image/tiff",
      "image/svg+xml",
      "application/octet-stream",
    ],
    allowedExtensions: [
      "jpg",
      "jpeg",
      "png",
      "webp",
      "avif",
      "gif",
      "heic",
      "heif",
      "bmp",
      "tiff",
      "jfif",
      "svg",
    ],
  },
  "property-documents": {
    maxSize: 30 * 1024 * 1024, // 30MB
    allowedMimes: [
      "application/pdf",
      "image/jpeg",
      "image/png",
      "image/webp",
      "image/jpg",
      "application/msword",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "application/octet-stream",
    ],
    allowedExtensions: ["pdf", "jpg", "jpeg", "png", "webp", "doc", "docx"],
  },
  "agency-logos": {
    maxSize: 10 * 1024 * 1024, // 10MB
    allowedMimes: [
      "image/jpeg",
      "image/png",
      "image/webp",
      "image/svg+xml",
      "image/jpg",
      "image/gif",
      "application/octet-stream",
    ],
    allowedExtensions: ["jpg", "jpeg", "png", "webp", "svg", "gif"],
  },
  avatars: {
    maxSize: 10 * 1024 * 1024, // 10MB
    allowedMimes: [
      "image/jpeg",
      "image/png",
      "image/webp",
      "image/jpg",
      "image/gif",
      "application/octet-stream",
    ],
    allowedExtensions: ["jpg", "jpeg", "png", "webp", "gif"],
  },
};

export async function POST(request: NextRequest) {
  try {
    const contentType = request.headers.get("content-type") || "";
    if (!contentType.includes("multipart/form-data")) {
      return NextResponse.json(
        { success: false, error: "Content-Type must be multipart/form-data" },
        { status: 400 }
      );
    }

    let formData: FormData;
    try {
      formData = await request.formData();
    } catch (parseErr) {
      console.error("[FormData Parse Error]:", parseErr);
      return NextResponse.json(
        {
          success: false,
          error: "Failed to process uploaded file. File may exceed server payload limits or was interrupted. Please ensure images are optimized.",
        },
        { status: 400 }
      );
    }

    // Verify authenticated user session
    const authSession = await auth();
    if (!authSession?.userId) {
      return NextResponse.json(
        { success: false, error: "Unauthorized: You must be signed in to upload files" },
        { status: 401 }
      );
    }

    const file = formData.get("file") as File | null;
    const bucket = (formData.get("bucket") as string) || "property-images";
    const requestedUserId = (formData.get("userId") as string) || authSession.userId;
    const userId = requestedUserId !== "anonymous" ? requestedUserId : authSession.userId;

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

    const config = BUCKET_CONFIGS[bucket] || BUCKET_CONFIGS["property-images"];

    // Validate size
    if (file.size > config.maxSize) {
      return NextResponse.json(
        {
          success: false,
          error: `File "${file.name}" exceeds maximum allowed size of ${Math.round(config.maxSize / (1024 * 1024))}MB`,
        },
        { status: 400 }
      );
    }

    // Validate mime type & file extension
    const fileExtension = file.name.split(".").pop()?.toLowerCase() || "";
    const mimeType = (file.type || "").toLowerCase();

    const isMimeAllowed = mimeType ? config.allowedMimes.includes(mimeType) : false;
    const isExtensionAllowed = fileExtension ? config.allowedExtensions.includes(fileExtension) : false;

    if (!isMimeAllowed && !isExtensionAllowed && mimeType !== "application/octet-stream" && mimeType !== "") {
      return NextResponse.json(
        {
          success: false,
          error: `File format "${file.type || fileExtension}" is not supported for ${bucket}. Supported: JPG, PNG, WEBP, HEIC, PDF.`,
        },
        { status: 400 }
      );
    }

    const supabase = createAdminClient();

    // Ensure bucket exists with public access
    try {
      const { data: buckets } = await supabase.storage.listBuckets();
      if (!buckets?.some((b) => b.id === bucket || b.name === bucket)) {
        await supabase.storage.createBucket(bucket, {
          public: true,
          fileSizeLimit: config.maxSize,
        });
      }
    } catch {
      // Ignore if list/create bucket fails due to permissions
    }

    const cleanFileName = file.name.replace(/[^a-zA-Z0-9.-]/g, "_");
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 10000);
    const storagePath = `properties/${userId}/${timestamp}-${random}-${cleanFileName}`;

    const arrayBuffer = await file.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);

    // Determine normalized Content-Type for Supabase Storage
    let finalContentType = file.type || "image/jpeg";
    if (!file.type || file.type === "application/octet-stream") {
      if (fileExtension === "png") finalContentType = "image/png";
      else if (fileExtension === "webp") finalContentType = "image/webp";
      else if (fileExtension === "gif") finalContentType = "image/gif";
      else if (fileExtension === "pdf") finalContentType = "application/pdf";
      else if (fileExtension === "svg") finalContentType = "image/svg+xml";
      else finalContentType = "image/jpeg";
    }

    const { error: uploadError } = await supabase.storage
      .from(bucket)
      .upload(storagePath, buffer, {
        contentType: finalContentType,
        cacheControl: "3600",
        upsert: true,
      });

    if (uploadError) {
      console.error("[Storage Upload Error via Admin Client]:", uploadError);
      return NextResponse.json(
        { success: false, error: uploadError.message },
        { status: 500 }
      );
    }

    const { data: publicUrlData } = supabase.storage
      .from(bucket)
      .getPublicUrl(storagePath);

    return NextResponse.json({
      success: true,
      url: publicUrlData.publicUrl,
      data: {
        url: publicUrlData.publicUrl,
        storagePath,
      },
      storagePath,
    });
  } catch (err: unknown) {
    console.error("[API Upload Route Error]:", err);
    const message = err instanceof Error ? err.message : "Internal Server Error";
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    );
  }
}
