/**
 * Contract mock of the compliance API (enabled with NEXT_PUBLIC_COMPLIANCE_MOCK=true).
 *
 * It plays the backend's role end to end so the page can be built and reviewed before
 * /api/admin/compliance/* exists: a deterministic dataset of vehicles across clients,
 * the same rules and scoring as the backend evaluator, filtering, sorting, pagination
 * and an in-memory alert log. Never enabled in production.
 */
import type {
  ComplianceRule,
  ComplianceStats,
  ComplianceVehicle,
  ComplianceVehicleDetail,
  ComplianceCompany,
  ComplianceAlert,
  ComplianceAlertPreview,
  ComplianceCategory,
  ComplianceCheck,
  ComplianceDeadline,
  ComplianceDeadlineStatus,
  ComplianceDeadlineType,
  ComplianceDocument,
  ComplianceFinancingMode,
  ComplianceStatus,
  SendComplianceAlertPayload,
  SendComplianceAlertResult,
} from "@/domain/entities/compliance";
import type { ComplianceRepository } from "@/domain/repositories/compliance.repository";
import type { BackendPaginatedData, PaginationQueryParams } from "@/shared/types";
import {
  COMPLIANCE_RULES,
  COMPLIANCE_RULE_BY_KEY,
  COMPLIANCE_SEVERITY_WEIGHT,
  COMPLIANCE_CATEGORIES,
  COMPLIANCE_CRITICAL_BELOW,
  COMPLIANCE_COMPLIANT_FROM,
} from "@/shared/constants/compliance";
import { messagesFr } from "@/shared/i18n/messages-fr";

// ── Deterministic random ─────────────────────────────────────────────────────

function mulberry32(seed: number) {
  let a = seed;
  return () => {
    a |= 0;
    a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const rand = mulberry32(20261005);
const chance = (p: number) => rand() < p;
const pick = <T,>(items: readonly T[]): T => items[Math.floor(rand() * items.length)];
const int = (min: number, max: number) => Math.floor(rand() * (max - min + 1)) + min;

const DAY = 86_400_000;
const NOW = Date.now();
const isoDate = (offsetDays: number) => new Date(NOW + offsetDays * DAY).toISOString().slice(0, 10);
const isoDateTime = (offsetDays: number) => new Date(NOW + offsetDays * DAY).toISOString();
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

// ── Dataset ──────────────────────────────────────────────────────────────────

const COMPANIES = [
  { id: 41, name: "Dadycar Demo", sites: ["Paris 15", "Lyon Part-Dieu"], admin: "Sophie Laurent", email: "fleet@dadycar-demo.fr", size: 34 },
  { id: 12, name: "Transports Martin", sites: ["Rungis", "Orly"], admin: "Julien Martin", email: "j.martin@transports-martin.fr", size: 28 },
  { id: 18, name: "Groupe Lefèvre BTP", sites: ["Nanterre", "Créteil", "Évry"], admin: "Claire Lefèvre", email: "parc@lefevre-btp.fr", size: 26 },
  { id: 23, name: "Clinique Saint-Roch", sites: ["Montpellier"], admin: "Dr. Marc Roux", email: "logistique@stroch.fr", size: 9 },
  { id: 27, name: "Atlantic Livraisons", sites: ["Nantes", "Saint-Nazaire"], admin: "Yann Le Goff", email: "flotte@atlantic-livraisons.fr", size: 22 },
  { id: 31, name: "Vertigo Énergie", sites: ["Grenoble"], admin: "Inès Benali", email: "i.benali@vertigo-energie.fr", size: 14 },
  { id: 35, name: "Boulangeries Dupain", sites: ["Lille", "Roubaix"], admin: "Thomas Dupain", email: "contact@dupain.fr", size: 11 },
  { id: 38, name: "Sécuri-Pro Services", sites: ["Marseille", "Aix"], admin: "Karim Haddad", email: "k.haddad@securipro.fr", size: 19 },
  { id: 44, name: "Agence Horizon Immo", sites: ["Bordeaux"], admin: "Léa Fontaine", email: "lea@horizon-immo.fr", size: 7 },
  { id: 47, name: "Medi-Sud Ambulances", sites: ["Toulouse", "Albi"], admin: "Paul Garcia", email: "direction@medisud.fr", size: 16 },
  { id: 52, name: "Nordis Logistique", sites: ["Dunkerque", "Calais"], admin: "Émilie Vasseur", email: "flotte@nordis.fr", size: 24 },
  { id: 55, name: "Café Lumière", sites: ["Paris 11"], admin: "Hugo Bernard", email: "hugo@cafe-lumiere.fr", size: 5 },
];

const MODELS = [
  { make_model: "Peugeot 208 II", fuel: "Essence", cat: "VP" },
  { make_model: "Peugeot 308 SW", fuel: "Diesel", cat: "VP" },
  { make_model: "Renault Clio V", fuel: "Essence", cat: "VP" },
  { make_model: "Renault Mégane E-Tech", fuel: "Électrique", cat: "VP" },
  { make_model: "Renault Kangoo Van", fuel: "Diesel", cat: "VU" },
  { make_model: "Citroën Berlingo Van", fuel: "Diesel", cat: "VU" },
  { make_model: "Peugeot Partner", fuel: "Diesel", cat: "VU" },
  { make_model: "Toyota Yaris Hybride", fuel: "Hybride", cat: "VP" },
  { make_model: "Tesla Model 3", fuel: "Électrique", cat: "VF" },
  { make_model: "Volkswagen Golf 8", fuel: "Essence", cat: "VP" },
  { make_model: "Ford Transit Custom", fuel: "Diesel", cat: "VU" },
  { make_model: "Dacia Spring", fuel: "Électrique", cat: "VP" },
  { make_model: "BMW Série 3 Touring", fuel: "Hybride", cat: "VF" },
  { make_model: "Fiat Ducato", fuel: "Diesel", cat: "VU" },
];

const LESSORS = ["Arval", "Ayvens", "Leasys", "Alphabet", "Free2Move Lease"];
const DRIVERS = ["Nadia Morel", "Lucas Petit", "Sarah Dubois", "Mehdi Saïdi", "Camille Robert", "Antoine Girard", "Fatou Diallo", "Romain Faure", "Laura Chevalier", "Kevin N'Guessan"];
const LETTERS = "ABCDEFGHJKLMNPQRSTVWXYZ";

function plate(): string {
  const l = () => LETTERS[int(0, LETTERS.length - 1)];
  return `${l()}${l()}-${String(int(100, 999))}-${l()}${l()}`;
}

function vin(): string {
  const chars = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
  let out = "VF";
  for (let i = 0; i < 15; i++) out += chars[int(0, chars.length - 1)];
  return out;
}

/** Raw facts of a vehicle, as the backend would read them from its tables. */
interface Facts {
  id: number;
  company: (typeof COMPANIES)[number];
  site: string | null;
  numberplate: string;
  vin: string | null;
  make_model: string;
  category: string | null;
  fuel: string | null;
  first_registration: string | null;
  age_years: number;
  park_entry: string | null;
  odometer: number | null;
  odometer_days: number | null;
  co2: number | null;
  crit_air: number | null;
  fiscal_power: number | null;
  aen_mode: "forfaitaire" | "reelle" | null;
  telematics: "connected" | "pending" | "disconnected";
  has_device: boolean;
  provider: string | null;
  financing: ComplianceFinancingMode | null;
  lessor: string | null;
  contract_number: string | null;
  contract_start: string | null;
  contract_end: string | null;
  km_limit: number | null;
  monthly_rent: number | null;
  duration: number | null;
  doc_cg: boolean;
  doc_ca: boolean;
  insurance_expiry: string | null;
  doc_cl: boolean;
  doc_invoice: boolean;
  doc_ct: boolean;
  doc_cj: boolean;
  driver: string | null;
  licence: "active" | "expiring_soon" | "expired" | null;
  licence_expiry: string | null;
  next_ct: string | null;
  next_maintenance: string | null;
  fuel_card: boolean;
  toll_badge: boolean;
  duplicate_keys: boolean;
  antai_enabled: boolean;
  antai_ok: boolean;
}

/** Per-company data quality, so the ranking has good and bad clients. */
const QUALITY: Record<number, number> = { 41: 0.74, 12: 0.8, 18: 0.68, 23: 0.95, 27: 0.84, 31: 0.97, 35: 0.62, 38: 0.88, 44: 0.98, 47: 0.9, 52: 0.77, 55: 0.58 };

function buildFacts(): Facts[] {
  const out: Facts[] = [];
  let id = 800;
  for (const company of COMPANIES) {
    const q = QUALITY[company.id] ?? 0.6;
    const has = (bias = 0) => chance(Math.min(0.98, q + bias));
    for (let i = 0; i < company.size; i++) {
      const model = pick(MODELS);
      const ev = model.fuel === "Électrique";
      const age = int(0, 9);
      const financing: ComplianceFinancingMode | null = has(0.25)
        ? pick(["lld", "lld", "lld", "loa", "credit", "cash"] as const)
        : null;
      const leasing = financing === "lld" || financing === "loa";
      const contractStart = -int(60, 1300);
      const contractEnd = contractStart + pick([36, 48, 60]) * 30;
      const driver = has(0.1) ? pick(DRIVERS) : null;
      const licenceRoll = rand();
      out.push({
        id: id++,
        company,
        site: has(0.3) ? pick(company.sites) : null,
        numberplate: plate(),
        vin: has(0.35) ? vin() : null,
        make_model: model.make_model,
        category: has(0.2) ? model.cat : null,
        fuel: has(0.4) ? model.fuel : null,
        first_registration: has(0.15) ? isoDate(-age * 365 - int(0, 300)) : null,
        age_years: age,
        park_entry: has(0.1) ? isoDate(-int(30, 900)) : null,
        odometer: has(0.3) ? int(2_000, 180_000) : null,
        odometer_days: has(0.1) ? int(0, 60) : int(91, 200),
        co2: ev ? 0 : has(-0.1) ? int(95, 210) : null,
        crit_air: has(0) ? (ev ? 0 : int(1, 3)) : null,
        fiscal_power: has(-0.05) ? int(4, 11) : null,
        aen_mode: driver && has(0) ? pick(["forfaitaire", "reelle"] as const) : null,
        telematics: has(0.1) ? "connected" : pick(["pending", "disconnected", "disconnected"] as const),
        has_device: has(0),
        provider: chance(0.6) ? pick(["OEM (LINKBYCAR)", "OEM (STELLANTIS)", "DEVICE (FLESPI)"]) : null,
        financing,
        lessor: leasing && has(0.2) ? pick(LESSORS) : null,
        contract_number: leasing && has(0.1) ? `${pick(["AR", "AY", "LS"])}-${int(100000, 999999)}` : null,
        contract_start: leasing && has(0.2) ? isoDate(contractStart) : null,
        contract_end: leasing && has(0.2) ? isoDate(contractEnd) : null,
        km_limit: leasing && has(0) ? pick([60_000, 90_000, 120_000, 150_000]) : null,
        monthly_rent: leasing && has(0.05) ? int(280, 790) : null,
        duration: leasing && has(0.1) ? pick([36, 48, 60]) : null,
        doc_cg: has(-0.15),
        doc_ca: has(0),
        insurance_expiry: chance(0.9) ? isoDate(has(0.1) ? int(20, 360) : int(-60, 19)) : null,
        doc_cl: leasing && has(-0.1),
        doc_invoice: (financing === "cash" || financing === "credit") && has(0),
        doc_ct: age >= 4 && has(-0.05),
        doc_cj: chance(0.3),
        driver,
        licence: driver ? (licenceRoll < 0.05 ? null : licenceRoll < 0.09 ? "expired" : licenceRoll < 0.18 ? "expiring_soon" : "active") : null,
        licence_expiry: driver ? isoDate(int(-90, 2500)) : null,
        next_ct: age >= 4 ? (has(0) ? isoDate(has(0) ? int(10, 600) : int(-120, 9)) : null) : null,
        next_maintenance: has(0.1) ? isoDate(has(0.05) ? int(5, 365) : int(-80, 4)) : null,
        fuel_card: !ev && chance(0.6),
        toll_badge: chance(0.4),
        duplicate_keys: chance(0.5),
        antai_enabled: chance(0.7),
        antai_ok: has(0.15),
      });
    }
  }

  // The vehicle from the agent audit: missing CO2, carte grise and the signed LLD contract.
  const demo = out.find((f) => f.company.id === 41);
  if (demo) {
    Object.assign(demo, {
      numberplate: "GC-673-QN",
      make_model: "Peugeot 208 II",
      fuel: "Essence",
      category: "VP",
      vin: "VF3UPHNSKMS204871",
      site: "Paris 15",
      co2: null,
      doc_cg: false,
      doc_ca: true,
      financing: "lld",
      lessor: "Arval",
      contract_number: "AR-551203",
      contract_start: isoDate(-700),
      contract_end: isoDate(395),
      km_limit: 90_000,
      monthly_rent: 389,
      duration: 36,
      doc_cl: false,
      telematics: "connected",
      has_device: true,
      provider: "OEM (STELLANTIS)",
      age_years: 2,
      first_registration: isoDate(-760),
      driver: "Nadia Morel",
      licence: "active",
    } satisfies Partial<Facts>);
  }
  return out;
}

// ── Rules (mirror of the backend evaluator) ─────────────────────────────────

const isCombustion = (f: Facts) => f.fuel !== "Électrique";
const isLeasing = (f: Facts) => f.financing === "lld" || f.financing === "loa";
const isPurchase = (f: Facts) => f.financing === "cash" || f.financing === "credit";
const days = (date: string) => Math.round((new Date(date).getTime() - NOW) / DAY);

function deadlineStatus(date: string): ComplianceDeadlineStatus {
  const d = days(date);
  if (d < 0) return "overdue";
  if (d <= 90) return "due_soon";
  return "upcoming";
}

type RuleCheck = { applies: (f: Facts) => boolean; passes: (f: Facts) => boolean; value?: (f: Facts) => string | null };

const always = () => true;
const CHECKS: Record<string, RuleCheck> = {
  "identity.numberplate": { applies: always, passes: (f) => !!f.numberplate, value: (f) => f.numberplate },
  "identity.vin": { applies: always, passes: (f) => f.vin?.length === 17, value: (f) => f.vin },
  "identity.make_model": { applies: always, passes: (f) => !!f.make_model, value: (f) => f.make_model },
  "identity.category": { applies: always, passes: (f) => !!f.category, value: (f) => f.category },
  "identity.first_registration": { applies: always, passes: (f) => !!f.first_registration, value: (f) => f.first_registration },
  "identity.park_entry": { applies: always, passes: (f) => !!f.park_entry, value: (f) => f.park_entry },
  "identity.site": { applies: always, passes: (f) => !!f.site, value: (f) => f.site },
  "identity.odometer": {
    applies: always,
    passes: (f) => f.odometer !== null && (f.odometer_days ?? 999) <= 90,
    value: (f) => (f.odometer !== null ? `${f.odometer.toLocaleString("fr-FR")} km` : null),
  },
  "fiscal.co2": { applies: isCombustion, passes: (f) => f.co2 !== null, value: (f) => (f.co2 !== null ? `${f.co2} g/km` : null) },
  "fiscal.energy": { applies: always, passes: (f) => !!f.fuel, value: (f) => f.fuel },
  "fiscal.crit_air": { applies: always, passes: (f) => f.crit_air !== null, value: (f) => (f.crit_air !== null ? `Crit'Air ${f.crit_air}` : null) },
  "fiscal.fiscal_power": { applies: always, passes: (f) => f.fiscal_power !== null, value: (f) => (f.fiscal_power !== null ? `${f.fiscal_power} CV` : null) },
  "fiscal.aen_mode": { applies: (f) => !!f.driver, passes: (f) => !!f.aen_mode, value: (f) => (f.aen_mode ? { forfaitaire: "Forfaitaire", reelle: "Frais réels" }[f.aen_mode] : null) },
  "telematics.connected": { applies: always, passes: (f) => f.telematics === "connected", value: (f) => ({ connected: "Connecté", pending: "Installation en attente", disconnected: "Déconnecté" })[f.telematics] },
  "telematics.device": { applies: always, passes: (f) => f.has_device || !!f.provider?.startsWith("OEM"), value: (f) => f.provider },
  "finance.mode": { applies: always, passes: (f) => !!f.financing, value: (f) => f.financing?.toUpperCase() ?? null },
  "finance.lessor": { applies: isLeasing, passes: (f) => !!f.lessor, value: (f) => f.lessor },
  "finance.contract_number": { applies: isLeasing, passes: (f) => !!f.contract_number, value: (f) => f.contract_number },
  "finance.contract_dates": { applies: isLeasing, passes: (f) => !!f.contract_start && !!f.contract_end, value: (f) => (f.contract_end ? `→ ${f.contract_end}` : null) },
  "finance.km_limit": { applies: isLeasing, passes: (f) => f.km_limit !== null, value: (f) => (f.km_limit ? `${f.km_limit.toLocaleString("fr-FR")} km` : null) },
  "finance.monthly_rent": { applies: isLeasing, passes: (f) => f.monthly_rent !== null, value: (f) => (f.monthly_rent ? `${f.monthly_rent} € HT` : null) },
  "finance.duration": { applies: isLeasing, passes: (f) => f.duration !== null, value: (f) => (f.duration ? `${f.duration} mois` : null) },
  "documents.carte_grise": { applies: always, passes: (f) => f.doc_cg },
  "documents.insurance": { applies: always, passes: (f) => f.doc_ca },
  "documents.insurance_valid": {
    applies: (f) => !!f.insurance_expiry,
    passes: (f) => !!f.insurance_expiry && days(f.insurance_expiry) >= 0,
    value: (f) => f.insurance_expiry,
  },
  "documents.leasing_contract": { applies: isLeasing, passes: (f) => f.doc_cl },
  "documents.purchase_invoice": { applies: isPurchase, passes: (f) => f.doc_invoice },
  "documents.technical_control": { applies: (f) => f.age_years >= 4, passes: (f) => f.doc_ct },
  "driver.assigned": { applies: always, passes: (f) => !!f.driver, value: (f) => f.driver },
  "driver.licence": { applies: (f) => !!f.driver, passes: (f) => f.licence === "active" || f.licence === "expiring_soon", value: (f) => (f.licence ? { active: "Valide", expiring_soon: "Expire bientôt", expired: "Expiré" }[f.licence] : null) },
  "deadline.technical_control": {
    applies: (f) => f.age_years >= 4,
    passes: (f) => !!f.next_ct && days(f.next_ct) >= 0,
    value: (f) => f.next_ct,
  },
  "deadline.maintenance": { applies: always, passes: (f) => !!f.next_maintenance && days(f.next_maintenance) >= 0, value: (f) => f.next_maintenance },
  "deadline.contract_end": { applies: (f) => isLeasing(f) && !!f.contract_end, passes: (f) => !!f.contract_end && days(f.contract_end) >= 0, value: (f) => f.contract_end },
  "antai.binding": { applies: (f) => f.antai_enabled, passes: (f) => f.antai_ok },
  "extras.fuel_card": { applies: isCombustion, passes: (f) => f.fuel_card },
  "extras.toll_badge": { applies: always, passes: (f) => f.toll_badge },
  "extras.duplicate_keys": { applies: always, passes: (f) => f.duplicate_keys },
};

interface Evaluated {
  facts: Facts;
  checks: ComplianceCheck[];
  row: ComplianceVehicle;
}

function scoreOf(checks: ComplianceCheck[]): number {
  let total = 0;
  let passed = 0;
  for (const c of checks) {
    if (!c.applicable) continue;
    const w = COMPLIANCE_SEVERITY_WEIGHT[c.severity];
    total += w;
    if (c.passed) passed += w;
  }
  return total === 0 ? 100 : Math.round((100 * passed) / total);
}

function statusOf(score: number, criticalMissing: number): ComplianceStatus {
  if (criticalMissing > 0 || score < COMPLIANCE_CRITICAL_BELOW) return "critical";
  if (score < COMPLIANCE_COMPLIANT_FROM) return "incomplete";
  return "compliant";
}

function deadlinesOf(f: Facts): ComplianceDeadline[] {
  const list: { type: ComplianceDeadlineType; date: string | null }[] = [
    { type: "technical_control", date: f.next_ct },
    { type: "maintenance", date: f.next_maintenance },
    { type: "contract_end", date: isLeasing(f) ? f.contract_end : null },
    { type: "insurance", date: f.insurance_expiry },
    { type: "licence", date: f.driver ? f.licence_expiry : null },
  ];
  return list
    .filter((d): d is { type: ComplianceDeadlineType; date: string } => !!d.date)
    .map((d) => ({ ...d, status: deadlineStatus(d.date) }))
    .sort((a, b) => a.date.localeCompare(b.date));
}

function evaluate(f: Facts, lastAlertAt: string | null): Evaluated {
  const checks: ComplianceCheck[] = COMPLIANCE_RULES.map((rule) => {
    const check = CHECKS[rule.key];
    const applicable = check.applies(f);
    return {
      key: rule.key,
      category: rule.category,
      severity: rule.severity,
      applicable,
      passed: applicable ? check.passes(f) : true,
      value: check.value?.(f) ?? null,
      detail: null,
    };
  });
  const failing = checks.filter((c) => c.applicable && !c.passed);
  const score = scoreOf(checks);
  const missing_count = {
    critical: failing.filter((c) => c.severity === "critical").length,
    high: failing.filter((c) => c.severity === "high").length,
    medium: failing.filter((c) => c.severity === "medium").length,
  };
  const category_scores: Partial<Record<ComplianceCategory, number>> = {};
  for (const cat of COMPLIANCE_CATEGORIES) {
    const inCat = checks.filter((c) => c.category === cat);
    if (inCat.some((c) => c.applicable)) category_scores[cat] = scoreOf(inCat);
  }
  const warnings: string[] = [];
  if (isLeasing(f) && f.contract_end && days(f.contract_end) >= 0 && days(f.contract_end) <= 90) warnings.push("deadline.contract_end");
  if (f.licence === "expiring_soon") warnings.push("driver.licence");

  const upcoming = deadlinesOf(f)[0] ?? null;
  return {
    facts: f,
    checks,
    row: {
      vehicle_id: f.id,
      numberplate: f.numberplate,
      vin: f.vin,
      make_model: f.make_model,
      fuel_type: f.fuel,
      company: { id: f.company.id, name: f.company.name },
      site: f.site ? { id: f.company.sites.indexOf(f.site) + f.company.id * 10, name: f.site } : null,
      score,
      status: statusOf(score, missing_count.critical),
      // Severity first, so the most important tags show first.
      missing: failing
        .sort((a, b) => COMPLIANCE_SEVERITY_WEIGHT[b.severity] - COMPLIANCE_SEVERITY_WEIGHT[a.severity])
        .map((c) => c.key),
      missing_count,
      warnings,
      category_scores,
      next_deadline: upcoming ? { type: upcoming.type, date: upcoming.date } : null,
      last_alert_at: lastAlertAt,
      computed_at: COMPUTED_AT,
    },
  };
}

// ── Store ────────────────────────────────────────────────────────────────────

const COMPUTED_AT = isoDateTime(-0.3);
const FACTS = buildFacts();
const ALERTS: ComplianceAlert[] = [];
let nextAlertId = 1;

function lastAlertFor(vehicleId: number): string | null {
  const alert = ALERTS.find((a) => a.vehicle?.id === vehicleId);
  return alert?.sent_at ?? null;
}

function allEvaluated(): Evaluated[] {
  return FACTS.map((f) => evaluate(f, lastAlertFor(f.id)));
}

// Seed some alert history (older alerts, some of them already resolved).
(() => {
  const evaluated = allEvaluated().filter((e) => e.row.status !== "compliant");
  for (let i = 0; i < 14; i++) {
    const e = evaluated[int(0, evaluated.length - 1)];
    const daysAgo = int(1, 40);
    ALERTS.push({
      id: nextAlertId++,
      company: e.row.company,
      vehicle: { id: e.row.vehicle_id, numberplate: e.row.numberplate },
      sent_by: pick(["Moncef B.", "M'hamed B.", "Badreddine M."]),
      channels: chance(0.6) ? ["email", "in_app"] : ["email"],
      recipients: [e.facts.company.email],
      missing: e.row.missing.slice(0, 4),
      score_at_send: Math.max(10, e.row.score - int(0, 15)),
      sent_at: isoDateTime(-daysAgo - rand()),
      resolved_at: chance(0.35) ? isoDateTime(-daysAgo + int(1, Math.max(1, daysAgo - 1))) : null,
    });
  }
  for (const company of [COMPANIES[1], COMPANIES[6]]) {
    ALERTS.push({
      id: nextAlertId++,
      company: { id: company.id, name: company.name },
      vehicle: null,
      sent_by: "Moncef B.",
      channels: ["email", "in_app"],
      recipients: [company.email],
      missing: ["fiscal.co2", "documents.carte_grise", "finance.mode"],
      score_at_send: null,
      sent_at: isoDateTime(-int(5, 25)),
      resolved_at: null,
    });
  }
  ALERTS.sort((a, b) => b.sent_at.localeCompare(a.sent_at));
})();

// ── Query helpers ────────────────────────────────────────────────────────────

function paginate<T>(items: T[], params: PaginationQueryParams): BackendPaginatedData<T> {
  const perPage = Number(params.per_page ?? 15);
  const page = Number(params.page ?? 1);
  const lastPage = Math.max(1, Math.ceil(items.length / perPage));
  const slice = items.slice((page - 1) * perPage, page * perPage);
  return {
    total: items.length,
    count: slice.length,
    per_page: perPage,
    current_page: page,
    last_page: lastPage,
    previous_page_url: page > 1 ? `?page=${page - 1}` : null,
    next_page_url: page < lastPage ? `?page=${page + 1}` : null,
    items: slice,
  };
}

function compare(a: string | number | null, b: string | number | null, desc: boolean): number {
  if (a === b) return 0;
  if (a === null) return 1;
  if (b === null) return -1;
  const result = a < b ? -1 : 1;
  return desc ? -result : result;
}

function filterVehicles(rows: ComplianceVehicle[], params: PaginationQueryParams): ComplianceVehicle[] {
  const search = String(params.search ?? "").trim().toLowerCase();
  const companyId = params.company_id ? Number(params.company_id) : null;
  const scoreMin = params.score_min !== undefined ? Number(params.score_min) : null;
  const scoreMax = params.score_max !== undefined ? Number(params.score_max) : null;
  return rows.filter((r) => {
    if (search && ![r.numberplate, r.vin ?? "", r.company.name, r.make_model].some((v) => v.toLowerCase().includes(search))) return false;
    if (companyId && r.company.id !== companyId) return false;
    if (params.status && r.status !== params.status) return false;
    if (params.missing && !r.missing.includes(String(params.missing))) return false;
    if (params.category && !r.missing.some((k) => COMPLIANCE_RULE_BY_KEY[k]?.category === params.category)) return false;
    if (params.severity && !r.missing.some((k) => COMPLIANCE_RULE_BY_KEY[k]?.severity === params.severity)) return false;
    if (params.fuel_type && r.fuel_type !== params.fuel_type) return false;
    if (scoreMin !== null && r.score < scoreMin) return false;
    if (scoreMax !== null && r.score > scoreMax) return false;
    return true;
  });
}

function ruleLabel(key: string): string {
  return (messagesFr.compliance.rules as Record<string, string>)[key] ?? key;
}

function vehicleBlock(row: ComplianceVehicle): string {
  const critical = row.missing.filter((k) => COMPLIANCE_RULE_BY_KEY[k]?.severity === "critical");
  const docs = row.missing.filter((k) => COMPLIANCE_RULE_BY_KEY[k]?.category === "documents");
  const others = row.missing.filter((k) => !critical.includes(k) && !docs.includes(k) && COMPLIANCE_RULE_BY_KEY[k]?.severity !== "low");
  const lines = [`Véhicule : ${row.numberplate} (${row.make_model})`, `Score de complétude actuel : ${row.score}%`, ""];
  const critNonDoc = critical.filter((k) => !docs.includes(k));
  if (critNonDoc.length) lines.push("⚠️ Données obligatoires manquantes :", ...critNonDoc.map((k) => `  • ${ruleLabel(k)}`), "");
  if (docs.length) lines.push("📄 Documents à joindre :", ...docs.map((k) => `  • ${ruleLabel(k)}`), "");
  if (others.length) lines.push("📝 Informations à compléter :", ...others.map((k) => `  • ${ruleLabel(k)}`), "");
  lines.push(`👉 Compléter la fiche : https://myfleet.dadycar.fr/fleet/vehicles/${row.vehicle_id}`);
  return lines.join("\n");
}

const WHY = [
  "Pourquoi est-ce important ?",
  "• L'absence du taux de CO2 bloque le calcul automatique de votre taxe TAI/TVS.",
  "• L'absence de la carte grise et de l'assurance expose vos conducteurs en cas de contrôle routier.",
  "• L'absence des données de contrat LLD vous expose à des pénalités kilométriques imprévues.",
].join("\n");

const RATE_LIMIT_DAYS = 7;

// ── Repository ───────────────────────────────────────────────────────────────

export class ComplianceRepositoryMock implements ComplianceRepository {
  async getRules(): Promise<ComplianceRule[]> {
    await sleep(120);
    return COMPLIANCE_RULES.map((r) => ({ ...r, label: ruleLabel(r.key) }));
  }

  async getStats(params?: { company_id?: number }): Promise<ComplianceStats> {
    await sleep(350);
    const rows = allEvaluated()
      .map((e) => e.row)
      .filter((r) => !params?.company_id || r.company.id === Number(params.company_id));
    const byCategory = Object.fromEntries(
      COMPLIANCE_CATEGORIES.map((cat) => {
        const missing = rows.filter((r) => r.missing.some((k) => COMPLIANCE_RULE_BY_KEY[k]?.category === cat)).length;
        return [cat, { complete: rows.length - missing, missing }];
      }),
    ) as ComplianceStats["by_category"];
    const ruleCounts = new Map<string, number>();
    for (const r of rows) for (const k of r.missing) ruleCounts.set(k, (ruleCounts.get(k) ?? 0) + 1);
    const deadlines = { overdue: 0, within_30: 0, within_60: 0, within_90: 0 };
    for (const r of rows) {
      if (!r.next_deadline) continue;
      const d = days(r.next_deadline.date);
      if (d < 0) deadlines.overdue++;
      else if (d <= 30) deadlines.within_30++;
      else if (d <= 60) deadlines.within_60++;
      else if (d <= 90) deadlines.within_90++;
    }
    const recent = ALERTS.filter(
      (a) => days(a.sent_at) >= -30 && (!params?.company_id || a.company.id === Number(params.company_id)),
    );
    return {
      total_vehicles: rows.length,
      average_score: rows.length ? Math.round(rows.reduce((s, r) => s + r.score, 0) / rows.length) : 0,
      by_status: {
        compliant: rows.filter((r) => r.status === "compliant").length,
        incomplete: rows.filter((r) => r.status === "incomplete").length,
        critical: rows.filter((r) => r.status === "critical").length,
      },
      by_category: byCategory,
      by_rule: [...ruleCounts.entries()]
        .map(([key, missing]) => ({ key, missing }))
        .sort((a, b) => b.missing - a.missing),
      deadlines,
      tax_blocked: ruleCounts.get("fiscal.co2") ?? 0,
      alerts: { sent_30d: recent.length, resolved_after_alert_30d: recent.filter((a) => a.resolved_at).length },
      computed_at: COMPUTED_AT,
    };
  }

  async getVehicles(params: PaginationQueryParams): Promise<BackendPaginatedData<ComplianceVehicle>> {
    await sleep(300);
    const rows = filterVehicles(allEvaluated().map((e) => e.row), params);
    const desc = params.order === "DESC";
    const orderBy = String(params.order_by ?? "score");
    const key = (r: ComplianceVehicle): string | number | null => {
      switch (orderBy) {
        case "numberplate": return r.numberplate;
        case "company": return r.company.name;
        case "next_deadline_at": return r.next_deadline?.date ?? null;
        case "last_alert_at": return r.last_alert_at;
        default: return r.score;
      }
    };
    rows.sort((a, b) => compare(key(a), key(b), desc) || a.numberplate.localeCompare(b.numberplate));
    return paginate(rows, params);
  }

  async getVehicle(vehicleId: number): Promise<ComplianceVehicleDetail> {
    await sleep(250);
    const f = FACTS.find((x) => x.id === vehicleId);
    if (!f) throw new Error("Vehicle not found");
    const { row, checks } = evaluate(f, lastAlertFor(f.id));
    const leasing = isLeasing(f);
    const purchase = isPurchase(f);
    const file = (type: string) => `${type}_${f.numberplate}.pdf`;
    const documents: ComplianceDocument[] = [
      { type: "CG", present: f.doc_cg, required: true, file_name: f.doc_cg ? file("carte_grise") : null, expiration_date: null, expiration_status: null },
      {
        type: "CA",
        present: f.doc_ca,
        required: true,
        file_name: f.doc_ca ? file("assurance") : null,
        expiration_date: f.insurance_expiry,
        expiration_status: f.insurance_expiry ? deadlineStatus(f.insurance_expiry) : null,
      },
      { type: "CL", present: f.doc_cl, required: leasing, file_name: f.doc_cl ? file("contrat_lld") : null, expiration_date: leasing ? f.contract_end : null, expiration_status: leasing && f.contract_end ? deadlineStatus(f.contract_end) : null },
      { type: "invoice", present: f.doc_invoice, required: purchase, file_name: f.doc_invoice ? file("facture") : null, expiration_date: null, expiration_status: null },
      { type: "CT", present: f.doc_ct, required: f.age_years >= 4, file_name: f.doc_ct ? file("pv_controle_technique") : null, expiration_date: f.next_ct, expiration_status: f.next_ct ? deadlineStatus(f.next_ct) : null },
      { type: "CJ", present: f.doc_cj, required: false, file_name: f.doc_cj ? file("carte_jaune") : null, expiration_date: null, expiration_status: null },
    ];
    return {
      ...row,
      checks,
      documents,
      deadlines: deadlinesOf(f),
      financing: {
        mode: f.financing,
        lessor: f.lessor,
        contract_number: f.contract_number,
        start_date: f.contract_start,
        end_date: f.contract_end,
        km_limit: f.km_limit,
        monthly_rent: f.monthly_rent,
        duration_months: f.duration,
      },
      driver: { name: f.driver, licence_status: f.licence, licence_expiry: f.driver ? f.licence_expiry : null },
      alerts: ALERTS.filter((a) => a.vehicle?.id === vehicleId),
      fleet_url: `https://myfleet.dadycar.fr/fleet/vehicles/${vehicleId}`,
    };
  }

  async getCompanies(params: PaginationQueryParams): Promise<BackendPaginatedData<ComplianceCompany>> {
    await sleep(300);
    const rows = allEvaluated().map((e) => e.row);
    const search = String(params.search ?? "").trim().toLowerCase();
    const companies: ComplianceCompany[] = COMPANIES.filter((c) => !search || c.name.toLowerCase().includes(search)).map((c) => {
      const own = rows.filter((r) => r.company.id === c.id);
      const counts = new Map<string, number>();
      for (const r of own) for (const k of r.missing) if (COMPLIANCE_RULE_BY_KEY[k]?.severity !== "low") counts.set(k, (counts.get(k) ?? 0) + 1);
      const last = ALERTS.find((a) => a.company.id === c.id);
      return {
        company: { id: c.id, name: c.name },
        vehicles: own.length,
        average_score: own.length ? Math.round(own.reduce((s, r) => s + r.score, 0) / own.length) : 0,
        critical: own.filter((r) => r.status === "critical").length,
        incomplete: own.filter((r) => r.status === "incomplete").length,
        compliant: own.filter((r) => r.status === "compliant").length,
        top_missing: [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([k]) => k),
        last_alert_at: last?.sent_at ?? null,
      };
    });
    const desc = params.order === "DESC";
    const orderBy = String(params.order_by ?? "average_score");
    const key = (c: ComplianceCompany): string | number | null => {
      switch (orderBy) {
        case "company": return c.company.name;
        case "vehicles": return c.vehicles;
        case "critical": return c.critical;
        case "last_alert_at": return c.last_alert_at;
        default: return c.average_score;
      }
    };
    companies.sort((a, b) => compare(key(a), key(b), desc));
    return paginate(companies, params);
  }

  async getAlerts(params: PaginationQueryParams): Promise<BackendPaginatedData<ComplianceAlert>> {
    await sleep(250);
    const search = String(params.search ?? "").trim().toLowerCase();
    const companyId = params.company_id ? Number(params.company_id) : null;
    const items = ALERTS.filter(
      (a) =>
        (!companyId || a.company.id === companyId) &&
        (!search || a.company.name.toLowerCase().includes(search) || (a.vehicle?.numberplate.toLowerCase().includes(search) ?? false)),
    );
    return paginate(items, params);
  }

  async getVehicleAlertPreview(vehicleId: number): Promise<ComplianceAlertPreview> {
    await sleep(250);
    const f = FACTS.find((x) => x.id === vehicleId);
    if (!f) throw new Error("Vehicle not found");
    const { row } = evaluate(f, lastAlertFor(f.id));
    const last = lastAlertFor(f.id);
    return {
      subject: `[Dadycar Fleet] Action requise : complétez le véhicule ${row.numberplate}`,
      body: ["Bonjour,", "", "Un véhicule de votre parc Dadycar Fleet est incomplet et nécessite des informations obligatoires pour assurer sa conformité légale et fiscale :", "", vehicleBlock(row), "", WHY, "", "L'équipe Support Dadycar Fleet"].join("\n"),
      recipients: [{ name: f.company.admin, email: f.company.email }],
      vehicles_count: 1,
      next_allowed_at: last && days(last) > -RATE_LIMIT_DAYS ? new Date(new Date(last).getTime() + RATE_LIMIT_DAYS * DAY).toISOString() : null,
    };
  }

  async sendVehicleAlert(vehicleId: number, payload: SendComplianceAlertPayload): Promise<SendComplianceAlertResult> {
    await sleep(500);
    const f = FACTS.find((x) => x.id === vehicleId);
    if (!f) throw new Error("Vehicle not found");
    const { row } = evaluate(f, lastAlertFor(f.id));
    const alert: ComplianceAlert = {
      id: nextAlertId++,
      company: row.company,
      vehicle: { id: row.vehicle_id, numberplate: row.numberplate },
      sent_by: "Vous",
      channels: payload.channels,
      recipients: [f.company.email],
      missing: row.missing,
      score_at_send: row.score,
      sent_at: new Date().toISOString(),
      resolved_at: null,
    };
    ALERTS.unshift(alert);
    return { alert_id: alert.id, sent_to: alert.recipients, channels: alert.channels };
  }

  async getCompanyAlertPreview(companyId: number): Promise<ComplianceAlertPreview> {
    await sleep(300);
    const company = COMPANIES.find((c) => c.id === companyId);
    if (!company) throw new Error("Company not found");
    const rows = allEvaluated()
      .map((e) => e.row)
      .filter((r) => r.company.id === companyId && r.status !== "compliant")
      .sort((a, b) => a.score - b.score);
    const last = ALERTS.find((a) => a.company.id === companyId && a.vehicle === null);
    return {
      subject: `[Dadycar Fleet] Action requise : ${rows.length} véhicule${rows.length > 1 ? "s" : ""} à compléter`,
      body: [
        "Bonjour,",
        "",
        `${rows.length} véhicule${rows.length > 1 ? "s" : ""} de votre parc Dadycar Fleet ${rows.length > 1 ? "sont incomplets" : "est incomplet"} et nécessite${rows.length > 1 ? "nt" : ""} des informations obligatoires :`,
        "",
        ...rows.map((r) => `${vehicleBlock(r)}\n\n──────────────`),
        "",
        WHY,
        "",
        "L'équipe Support Dadycar Fleet",
      ].join("\n"),
      recipients: [{ name: company.admin, email: company.email }],
      vehicles_count: rows.length,
      next_allowed_at: last && days(last.sent_at) > -RATE_LIMIT_DAYS ? new Date(new Date(last.sent_at).getTime() + RATE_LIMIT_DAYS * DAY).toISOString() : null,
    };
  }

  async sendCompanyAlert(companyId: number, payload: SendComplianceAlertPayload): Promise<SendComplianceAlertResult> {
    await sleep(600);
    const company = COMPANIES.find((c) => c.id === companyId);
    if (!company) throw new Error("Company not found");
    const missing = new Set<string>();
    for (const e of allEvaluated()) if (e.row.company.id === companyId) e.row.missing.forEach((k) => missing.add(k));
    const alert: ComplianceAlert = {
      id: nextAlertId++,
      company: { id: company.id, name: company.name },
      vehicle: null,
      sent_by: "Vous",
      channels: payload.channels,
      recipients: [company.email],
      missing: [...missing],
      score_at_send: null,
      sent_at: new Date().toISOString(),
      resolved_at: null,
    };
    ALERTS.unshift(alert);
    return { alert_id: alert.id, sent_to: alert.recipients, channels: alert.channels };
  }

  async recompute(companyId?: number): Promise<{ queued: number }> {
    await sleep(400);
    return { queued: FACTS.filter((f) => !companyId || f.company.id === companyId).length };
  }
}
