import { NextRequest, NextResponse } from "next/server";
import { getPrisma } from "../../../../lib/db";
import { getSession } from "../../../../lib/auth/session";

export async function GET(req: NextRequest) {
  const auth = await getSession();
  if (!auth || auth.role !== "ADMIN") {
    return NextResponse.json({ ok: false, message: "Unauthorized" }, { status: 401 });
  }

  try {
    const prisma = await getPrisma();
    if (!prisma) {
      return NextResponse.json(
        { ok: false, message: "Database not available" },
        { status: 503 }
      );
    }

    const messages = await prisma.contactMessage.findMany({
      orderBy: { createdAt: "desc" },
    });

    return NextResponse.json({ ok: true, messages });
  } catch (error) {
    console.error("[ADMIN] Failed to fetch contact messages:", error);
    return NextResponse.json(
      { ok: false, message: "Failed to fetch messages" },
      { status: 500 }
    );
  }
}
