import "server-only";
import { corePool } from "./mysql";

/* ================================
   JOBS — ESPACE CANDIDAT
================================ */

export async function listPublicJobs({ limit = 50 } = {}) {
  const [rows] = await corePool.query(
    `
    SELECT
      id,
      title,
      company_name,
      location,
      contract_type,
      seniority_level,
      salary_min,
      salary_max,
      remote_allowed,
      is_urgent,
      aide_regionale,
      created_at
    FROM jobs
    WHERE status = 'published'
    ORDER BY created_at DESC
    LIMIT ?
    `,
    [limit]
  );

  return (rows as any[]).map(normalizeJob);
}

export async function getPublicJobById(id: number) {
  const [rows] = await corePool.query(
    `
    SELECT
      id,
      title,
      company_name,
      location,
      contract_type,
      seniority_level,
      salary_min,
      salary_max,
      remote_allowed,
      is_urgent,
      aide_regionale,
      description,
      missions,
      profile,
      skills,
      created_at
    FROM jobs
    WHERE id = ?
      AND status = 'published'
    LIMIT 1
    `,
    [id]
  );

  const job = (rows as any[])[0];
  return job ? normalizeJob(job) : null;
}

/* ================================
   NORMALISATION
================================ */

function normalizeJob(row: any) {
  return {
    ...row,
    skills: typeof row.skills === "string"
      ? row.skills.split(",").map((s: string) => s.trim()).filter(Boolean)
      : [],
  };
}
