/**
 * Staff Jobs Management API
 * GET: List all jobs (including drafts) - STAFF+
 * POST: Create new job - ADMIN+ only
 */

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

// Verify staff session and return user or error response
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/jobs
 * List all jobs with optional filtering
 */
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"); // draft, open, paused, closed, archived
  const department = searchParams.get("department");
  const search = searchParams.get("search");
  const page = parseInt(searchParams.get("page") || "1");
  const limit = parseInt(searchParams.get("limit") || "20");
  const offset = (page - 1) * limit;

  try {
    // Build where clause for prisma
    const where: Record<string, unknown> = {};
    if (status) {
      where.status = status;
    }
    if (department) {
      where.department = department;
    }

    const [jobs, count] = await Promise.all([
      prisma.jobs.findMany({
        where,
        orderBy: { created_at: "desc" },
        skip: offset,
        take: limit,
      }),
      prisma.jobs.count({ where }),
    ]);

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

/**
 * POST /api/staff/jobs
 * Create new job posting - ADMIN+ only
 */
export async function POST(request: NextRequest) {
  // Verify ADMIN or SUPER_ADMIN role
  const authResult = await verifyStaffAuth(["ADMIN", "SUPER_ADMIN"]);
  if ("error" in authResult) return authResult.error;

  try {
    const body = await request.json();

    // Required fields validation
    const requiredFields = [
      "slug",
      "title_translations",
      "department",
      "department_label",
      "location_translations",
      "contract_type",
      "contract_type_label",
      "level",
      "level_label",
      "compensation_translations",
      "responsibilities",
    ];

    for (const field of requiredFields) {
      if (!body[field]) {
        return NextResponse.json(
          { error: `Missing required field: ${field}` },
          { status: 400 },
        );
      }
    }

    // Validate bilingual fields have both ar and en
    const bilingualFields = [
      "title_translations",
      "department_label",
      "location_translations",
      "contract_type_label",
      "level_label",
      "compensation_translations",
    ];

    for (const field of bilingualFields) {
      const value = body[field];
      if (!value?.ar || !value?.en) {
        return NextResponse.json(
          { error: `${field} must include both 'ar' and 'en' translations` },
          { status: 400 },
        );
      }
    }

    const jobData = {
      slug: body.slug,
      title_translations: body.title_translations,
      department: body.department,
      department_label: body.department_label,
      location_translations: body.location_translations,
      contract_type: body.contract_type,
      contract_type_label: body.contract_type_label,
      level: body.level,
      level_label: body.level_label,
      compensation_translations: body.compensation_translations,
      benefits: body.benefits || {},
      skills: body.skills || {},
      requirements: body.requirements || {},
      responsibilities: body.responsibilities,
      nice_to_have: body.nice_to_have || {},
      workday_expectations: body.workday_expectations || {},
      application_instructions: body.application_instructions || {},
      status: body.status || "draft",
      opening_at: body.opening_at || new Date().toISOString(),
      closing_at: body.closing_at || null,
    };

    const job = await prisma.jobs.create({
      data: jobData,
    });

    logger.info("Job created by staff", {
      jobId: job.id,
      title: job.title_translations,
      createdBy: authResult.user.email,
    });

    return NextResponse.json({ job }, { status: 201 });
  } catch (error) {
    logger.error("Staff jobs POST error", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
