import { NextResponse } from "next/server";
import { writeFile } from "node:fs/promises";
import path from "node:path";
import { auth } from "@/auth";
import { prisma } from "@/lib/prisma";
import {
  chatDir,
  ensureDir,
  kindForMime,
  isAllowedUploadMime,
  makeStoredName,
  MAX_FILE_BYTES,
} from "@/lib/upload";

export async function POST(
  req: Request,
  { params }: { params: Promise<{ channelId: string }> },
) {
  const session = await auth();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  if (!session.user.permissions?.includes("chat.send")) {
    return NextResponse.json({ error: "Keine Berechtigung." }, { status: 403 });
  }

  const { channelId } = await params;

  // Mitgliedschaft prüfen.
  const member = await prisma.channelMember.findUnique({
    where: { channelId_userId: { channelId, userId: session.user.id } },
    select: { channelId: true },
  });
  if (!member) {
    return NextResponse.json({ error: "Kein Zugriff." }, { status: 404 });
  }

  const form = await req.formData();
  const file = form.get("file");
  if (!(file instanceof File)) {
    return NextResponse.json({ error: "Keine Datei." }, { status: 400 });
  }
  if (!isAllowedUploadMime(file.type)) {
    return NextResponse.json({ error: "Dateityp nicht erlaubt." }, { status: 400 });
  }
  if (file.size > MAX_FILE_BYTES) {
    return NextResponse.json({ error: "Datei zu groß (max. 15 MB)." }, { status: 400 });
  }

  const storedName = makeStoredName(file.type);
  const dir = chatDir(channelId);
  await ensureDir(dir);
  await writeFile(path.join(dir, storedName), Buffer.from(await file.arrayBuffer()));

  const toInt = (v: FormDataEntryValue | null) => {
    const n = Number(v);
    return Number.isFinite(n) && n > 0 ? Math.round(n) : null;
  };

  return NextResponse.json({
    storedName,
    kind: kindForMime(file.type),
    mime: file.type,
    size: file.size,
    originalName: file.name.slice(0, 255),
    width: toInt(form.get("width")),
    height: toInt(form.get("height")),
    durationMs: toInt(form.get("durationMs")),
  });
}
