import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { PutObjectCommand } from "@aws-sdk/client-s3";
import { v4 as uuidv4 } from "uuid";
import { s3Client, S3_BUCKET, getPublicUrl } from "@/lib/s3";
import { MAX_FILE_SIZE, detectImageType } from "@/lib/upload";
import { uploadLimiter, rateLimitHeaders } from "@/lib/rate-limit";

function clientIp(req: NextRequest): string {
  const fwd = req.headers.get("x-forwarded-for");
  if (fwd) return fwd.split(",")[0].trim();
  return req.headers.get("x-real-ip") || "unknown";
}

export async function POST(req: NextRequest) {
  const ip = clientIp(req);
  const limit = uploadLimiter.limit(`upload:${ip}`);
  if (!limit.success) {
    return NextResponse.json(
      { error: "Премногу обиди. Обидете се повторно подоцна." },
      { status: 429, headers: rateLimitHeaders(limit) }
    );
  }

  const { userId } = await auth();
  if (!userId) {
    return NextResponse.json({ error: "Неавторизирано" }, { status: 401 });
  }

  try {
    const formData = await req.formData();
    const file = formData.get("file") as File | null;

    if (!file) {
      return NextResponse.json({ error: "Нема подадено датотека" }, { status: 400 });
    }

    if (file.size > MAX_FILE_SIZE) {
      return NextResponse.json({ error: "Датотеката е премногу голема (макс. 5MB)" }, { status: 400 });
    }

    const buffer = Buffer.from(await file.arrayBuffer());
    const detected = detectImageType(buffer);
    if (!detected) {
      return NextResponse.json(
        { error: "Невалиден тип на датотека. Дозволени: JPEG, PNG, WebP." },
        { status: 400 }
      );
    }

    const ext = detected.split("/")[1];
    const key = `uploads/${userId}/${uuidv4()}.${ext === "jpeg" ? "jpg" : ext}`;

    await s3Client.send(
      new PutObjectCommand({
        Bucket: S3_BUCKET,
        Key: key,
        Body: buffer,
        ContentType: detected,
      })
    );

    const publicUrl = getPublicUrl(key);

    return NextResponse.json({ key, url: publicUrl });
  } catch (error) {
    console.error("Upload error:", error);
    return NextResponse.json({ error: "Не успеа качувањето" }, { status: 500 });
  }
}
