/**
 * Staff Individual Job Management API
 * GET: Get single job - STAFF+
 * PUT: Update job - ADMIN+
 * DELETE: Delete job - SUPER_ADMIN only
 */

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/jobs/[id]
 * Fetch single job details
 */
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  const authResult = await verifyStaffAuth();
  if ("error" in authResult) return authResult.error;

  const { id } = params;

  try {
    const job = await prisma.jobs.findUnique({
      where: { id },
    });

    if (!job) {
      return NextResponse.json({ error: "Job not found" }, { status: 404 });
    }

    // Get application count for this job
    const applicationsCount = await prisma.job_applications.count({
      where: { job_id: id },
    });

    return NextResponse.json({
      job,
      applicationsCount: applicationsCount || 0,
    });
  } catch (error) {
    logger.error("Staff job GET error", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}

/**
 * PUT /api/staff/jobs/[id]
 * Update job - ADMIN+ only
 */
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  const authResult = await verifyStaffAuth(["ADMIN", "SUPER_ADMIN"]);
  if ("error" in authResult) return authResult.error;

  const { id } = params;

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

    // Validate bilingual fields if they're being updated
    const bilingualFields = [
      "title_translations",
      "department_label",
      "location_translations",
      "contract_type_label",
      "level_label",
      "compensation_translations",
    ];

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

    // Prepare update data (only include fields that are provided)
    const updateData: Record<string, unknown> = {};
    const allowedFields = [
      "slug",
      "title_translations",
      "department",
      "department_label",
      "location_translations",
      "contract_type",
      "contract_type_label",
      "level",
      "level_label",
      "compensation_translations",
      "benefits",
      "skills",
      "requirements",
      "responsibilities",
      "nice_to_have",
      "workday_expectations",
      "application_instructions",
      "status",
      "opening_at",
      "closing_at",
    ];

    for (const field of allowedFields) {
      if (body[field] !== undefined) {
        updateData[field] = body[field];
      }
    }

    const job = await prisma.jobs.update({
      where: { id },
      data: updateData,
    });

    logger.info("Job updated by staff", {
      jobId: id,
      updatedBy: authResult.user.email,
      changes: Object.keys(updateData),
    });

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

/**
 * DELETE /api/staff/jobs/[id]
 * Soft delete job (archive) - SUPER_ADMIN only
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  const authResult = await verifyStaffAuth(["SUPER_ADMIN"]);
  if ("error" in authResult) return authResult.error;

  const { id } = params;

  try {
    // Soft delete by setting status to 'archived'
    const job = await prisma.jobs.update({
      where: { id },
      data: { status: "archived" },
    });

    logger.info("Job archived by SUPER_ADMIN", {
      jobId: id,
      archivedBy: authResult.user.email,
    });

    return NextResponse.json({
      success: true,
      message: "Job archived successfully",
      job,
    });
  } catch (error) {
    logger.error("Staff job DELETE error", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
