import { NextRequest, NextResponse } from "next/server";
import { requireRecruiter } from "@/lib/auth/requireRecruiter";
import { JobCreateSchema } from "@/lib/validation/job.schema";
import { zodErrorResponse } from "@/lib/validation/zod-error";
import { corePool } from "@/lib/db/mysql";
import { auditLog } from "@/lib/audit/log";
import { rateLimit } from "@/lib/security/rateLimit";

export async function POST(req: NextRequest) {
  try {
    // 1️⃣ Rate limit (sensible)
    const limited = rateLimit(req, "sensitive");
    if (limited) return limited;

    // 2️⃣ Auth
    const recruiter = await requireRecruiter(req);

    // 3️⃣ Validation
    const body = await req.json();
    const data = JobCreateSchema.parse(body);

    // 4️⃣ Métier
    const [result]: any = await corePool.query(
      `
      INSERT INTO jobs (
        title,
        company_name,
        description,
        missions,
        profile,
        skills,
        location,
        contract_type,
        salary_min,
        salary_max,
        is_urgent,
        aide_regionale,
        status,
        created_by,
        company_id
      )
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft', ?, ?)
      `,
      [
        data.title,
        data.company_name,
        data.description,
        data.missions,
        data.profile,
        data.skills ? data.skills.join(", ") : null,
        data.location,
        data.contract_type,
        data.salary_min,
        data.salary_max,
        data.is_urgent ? 1 : 0,
        data.aide_regionale,
        recruiter.id,
        recruiter.company_id,
      ]
    );

    // 5️⃣ Audit
    await auditLog({
      actor_type: "recruiter",
      actor_id: recruiter.id,
      action: "job_created",
      entity: "job",
      entity_id: result.insertId,
      req,
    });

    return NextResponse.json({ success: true });
  } catch (err: any) {
    if (err.name === "ZodError") {
      return zodErrorResponse(err);
    }

    if (err.message === "unauthorized") {
      return NextResponse.json({ error: "unauthorized" }, { status: 401 });
    }

    console.error(err);
    return NextResponse.json({ error: "internal_error" }, { status: 500 });
  }
}
