/**
 * Staff Job Applications Management API
 * GET: List all applications with filters - STAFF+
 */

import { NextRequest, NextResponse } from "next/server";
import { getStaffSession } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";

async function verifyStaffAuth(
  requiredRoles: string[] = ["STAFF", "ADMIN", "SUPER_ADMIN"],
) {
  const user = await getStaffSession();

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

  if (!requiredRoles.includes(user.role)) {
    return {
      error: NextResponse.json(
        { error: "Insufficient permissions" },
        { status: 403 },
      ),
    };
  }

  return { user, role: user.role };
}

/**
 * GET /api/staff/applications
 * List all job applications with filtering and job details
 */
export async function GET(request: NextRequest) {
  const authResult = await verifyStaffAuth();
  if ("error" in authResult) return authResult.error;

  const { searchParams } = new URL(request.url);
  const status = searchParams.get("status"); // new, shortlisted, interview_scheduled, hired, rejected
  const jobId = searchParams.get("jobId");
  const search = searchParams.get("search"); // Search by applicant name or email
  const page = parseInt(searchParams.get("page") || "1");
  const limit = parseInt(searchParams.get("limit") || "20");
  const offset = (page - 1) * limit;

  try {
    // Build where clause
    const where: Record<string, unknown> = {};
    if (status) {
      where.status = status;
    }
    if (jobId) {
      where.job_id = jobId;
    }
    if (search) {
      where.OR = [
        { applicant_name: { contains: search, mode: "insensitive" } },
        { applicant_email: { contains: search, mode: "insensitive" } },
      ];
    }

    const [applications, count] = await Promise.all([
      prisma.job_applications.findMany({
        where,
        orderBy: { submitted_at: "desc" },
        skip: offset,
        take: limit,
        include: {
          jobs: {
            select: {
              id: true,
              slug: true,
              title_translations: true,
              department: true,
              department_label: true,
              location_translations: true,
              status: true,
            },
          },
        },
      }),
      prisma.job_applications.count({ where }),
    ]);

    // Get summary statistics
    const [newCount, shortlistedCount, interviewCount, hiredCount, rejectedCount] =
      await Promise.all([
        prisma.job_applications.count({ where: { status: "new" } }),
        prisma.job_applications.count({ where: { status: "shortlisted" } }),
        prisma.job_applications.count({ where: { status: "interview_scheduled" } }),
        prisma.job_applications.count({ where: { status: "hired" } }),
        prisma.job_applications.count({ where: { status: "rejected" } }),
      ]);

    const stats = {
      total: count || 0,
      new: newCount,
      shortlisted: shortlistedCount,
      interview_scheduled: interviewCount,
      hired: hiredCount,
      rejected: rejectedCount,
    };

    return NextResponse.json({
      applications: applications || [],
      stats,
      pagination: {
        page,
        limit,
        total: count || 0,
        totalPages: Math.ceil((count || 0) / limit),
      },
    });
  } catch (error) {
    logger.error("Staff applications GET error", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
