import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";

export async function GET(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    
    const comments = await prisma.comment.findMany({
      where: { mediaId: id },
      orderBy: { createdAt: "desc" },
      include: {
        user: { select: { id: true, name: true, image: true, role: true, isVerified: true } }
      }
    });

    return NextResponse.json(comments);
  } catch (error) {
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}

export async function POST(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth();
    const { id } = await params;

    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await req.json();
    if (!body.content || body.content.trim() === "") {
      return NextResponse.json({ error: "Content is required" }, { status: 400 });
    }

    const comment = await prisma.comment.create({
      data: {
        content: body.content,
        mediaId: id,
        userId: session.user.id
      },
      include: {
        user: { select: { id: true, name: true, image: true, role: true, isVerified: true } }
      }
    });

    // Add notification for uploader if it's not self-comment
    const media = await prisma.media.findUnique({ where: { id }, select: { uploaderId: true } });
    if (media && media.uploaderId && media.uploaderId !== session.user.id) {
      await prisma.notification.create({
        data: {
          userId: media.uploaderId,
          type: "COMMENT",
          message: `${session.user.name || "Quelqu'un"} a commenté votre vidéo`,
          link: `/video/${id}`
        }
      }).catch(() => {});
    }

    return NextResponse.json(comment);
  } catch (error) {
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}
