import { promises as fs } from "fs";
import path from "path";
import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";

const MEDIA_DIR = path.join(process.cwd(), "data", "media");

const ALLOWED_IMAGE = new Set(["image/png", "image/jpeg", "image/webp"]);
const ALLOWED_VIDEO = new Set(["video/mp4"]);
const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
const MAX_VIDEO_BYTES = 100 * 1024 * 1024;

export async function POST(request: Request) {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const formData = await request.formData();
  const file = formData.get("file");
  if (!(file instanceof File)) {
    return NextResponse.json({ error: "file is required" }, { status: 400 });
  }

  const isVideo = ALLOWED_VIDEO.has(file.type);
  const isImage = ALLOWED_IMAGE.has(file.type);
  if (!isImage && !isVideo) {
    return NextResponse.json(
      { error: "Allowed types: PNG, JPEG, WebP, MP4" },
      { status: 400 },
    );
  }

  const maxBytes = isVideo ? MAX_VIDEO_BYTES : MAX_IMAGE_BYTES;
  if (file.size > maxBytes) {
    return NextResponse.json({ error: "File exceeds size limit" }, { status: 400 });
  }

  const ext = isVideo ? "mp4" : file.type.split("/")[1]?.replace("jpeg", "jpg") ?? "bin";
  const filename = `${user.id.slice(0, 8)}-${Date.now()}-${crypto.randomUUID().slice(0, 8)}.${ext}`;

  await fs.mkdir(MEDIA_DIR, { recursive: true });
  const buffer = Buffer.from(await file.arrayBuffer());
  await fs.writeFile(path.join(MEDIA_DIR, filename), buffer);

  const url = `/api/media/${filename}`;
  return NextResponse.json({
    url,
    filename,
    mediaType: isVideo ? "video" : "image",
  });
}
