import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

export async function GET(req: NextRequest) {
  const session = await auth();

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

  const { searchParams } = req.nextUrl;
  const limit = Math.min(parseInt(searchParams.get("limit") || "50", 10), 100);
  const offset = parseInt(searchParams.get("offset") || "0", 10);

  try {
    const [feedback, total] = await Promise.all([
      db.feedback.findMany({
        where: { userId: session.user.id },
        orderBy: { createdAt: "desc" },
        take: limit,
        skip: offset,
      }),
      db.feedback.count({ where: { userId: session.user.id } }),
    ]);

    return NextResponse.json({ feedback, total });
  } catch {
    return NextResponse.json(
      { error: "Failed to fetch feedback" },
      { status: 500 }
    );
  }
}

export async function POST(req: NextRequest) {
  const session = await auth();

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

  try {
    const body = await req.json();
    const { requestId, rating, thumbsUp, comment, model } = body;

    // Validate thumbsUp (required boolean)
    if (typeof thumbsUp !== "boolean") {
      return NextResponse.json(
        { error: "thumbsUp must be a boolean" },
        { status: 400 }
      );
    }

    // Validate rating if provided (1-5)
    if (rating !== undefined && rating !== null) {
      if (!Number.isInteger(rating) || rating < 1 || rating > 5) {
        return NextResponse.json(
          { error: "Rating must be an integer between 1 and 5" },
          { status: 400 }
        );
      }
    }

    // Validate comment length if provided
    if (comment !== undefined && comment !== null) {
      if (typeof comment !== "string" || comment.length > 1000) {
        return NextResponse.json(
          { error: "Comment must be a string of 1000 characters or less" },
          { status: 400 }
        );
      }
    }

    const feedback = await db.feedback.create({
      data: {
        userId: session.user.id,
        requestId: requestId || null,
        rating: rating ?? null,
        thumbsUp,
        comment: comment || null,
        model: model || null,
      },
    });

    return NextResponse.json({ feedback }, { status: 201 });
  } catch {
    return NextResponse.json(
      { error: "Failed to create feedback" },
      { status: 500 }
    );
  }
}
