import { atsPool } from '@/lib/db/mysql';

/**
 * Génère les match_candidates pour un job donné
 * Hypothèse V1 :
 * - tous les candidats actifs sont éligibles
 * - score simple basé sur l'existence d'une analyse ATS
 */
export async function runMatchingForJob(jobId: number) {
  // 1) récupérer le match existant
  const [[match]]: any = await atsPool.query(
    `
    SELECT id
    FROM matches
    WHERE job_id = ?
    LIMIT 1
    `,
    [jobId]
  );

  if (!match) {
    throw new Error('MATCH_NOT_FOUND');
  }

  const matchId = match.id;

  // 2) récupérer les candidats éligibles
  const [candidates]: any = await atsPool.query(
    `
    SELECT DISTINCT c.id AS candidate_id
    FROM candidates c
    INNER JOIN candidate_documents cd
      ON cd.candidate_id = c.id
     AND cd.type = 'cv'
    `
  );

  if (!candidates.length) {
    return { inserted: 0 };
  }

  // 3) éviter les doublons
  const [existing]: any = await atsPool.query(
    `
    SELECT candidate_id
    FROM match_candidates
    WHERE match_id = ?
    `,
    [matchId]
  );

  const existingIds = new Set(existing.map((r: any) => r.candidate_id));

  // 4) insertion
  let inserted = 0;

  for (const c of candidates) {
    if (existingIds.has(c.candidate_id)) continue;

    // score V1 simple (sera amélioré)
    const [[analysis]]: any = await atsPool.query(
      `
      SELECT score
      FROM analysis_results
      WHERE candidate_id = ?
      ORDER BY created_at DESC
      LIMIT 1
      `,
      [c.candidate_id]
    );

    const score = analysis?.score ?? 50;

    await atsPool.query(
      `
      INSERT INTO match_candidates
      (match_id, candidate_id, ats_score, status)
      VALUES (?, ?, ?, 'pending')
      `,
      [matchId, c.candidate_id, score]
    );

    inserted++;
  }

  return { inserted };
}
