import { NextResponse } from "next/server";
import { writeFile } from "node:fs/promises";
import { randomBytes } from "node:crypto";
import path from "node:path";
import { auth } from "@/auth";
import { prisma } from "@/lib/prisma";
import { extForMime, isImageMime, MAX_AVATAR_BYTES, uploadDir } 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 });
  }

  const { channelId } = await params;

  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 channel = await prisma.channel.findUnique({
    where: { id: channelId },
    select: { type: true },
  });
  if (!channel || channel.type === "DIRECT") {
    return NextResponse.json(
      { error: "Für diesen Kanal nicht möglich." },
      { status: 400 },
    );
  }

  const form = await req.formData();
  const file = form.get("file");
  if (!(file instanceof File)) {
    return NextResponse.json({ error: "Keine Datei." }, { status: 400 });
  }
  if (!isImageMime(file.type)) {
    return NextResponse.json({ error: "Nur Bilder erlaubt." }, { status: 400 });
  }
  if (file.size > MAX_AVATAR_BYTES) {
    return NextResponse.json({ error: "Bild zu groß (max. 4 MB)." }, { status: 400 });
  }

  const dir = await uploadDir("channels");
  const name = `c-${channelId}-${randomBytes(4).toString("hex")}.${extForMime(file.type)}`;
  await writeFile(path.join(dir, name), Buffer.from(await file.arrayBuffer()));

  const url = `/uploads/channels/${name}`;
  await prisma.channel.update({ where: { id: channelId }, data: { avatarUrl: url } });

  return NextResponse.json({ url });
}
