import { AppDataSource } from '../config/database';
import { Player } from '../models/Player';
import { PlayerHealth } from '../models/PlayerHealth';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerGauges } from '../models/PlayerGauges';
import { PlayerSkills } from '../models/PlayerSkills';
import { GangMember } from '../models/GangMember';
import { MAP_ACTIONS, DONATION_RULES, MapAction } from '../constants/map-actions';
import { findWeapon } from '../constants/weapons';
import { PlayerInventory } from '../models/PlayerInventory';
import { VisibilityService } from './visibility.service';
import { TransactionService } from './transaction.service';
// Phase 8.5d.3 (2026-05-01) — Sync PV : HealthService.setHp + healToFull
// écrivent BOTH physical_health (PlayerHealth) ET sante_physique (PlayerGauges)
// pour éviter la désynchronisation entre PV interne et jauge UI.
import { HealthService } from './health.service';

export interface ActionResult {
  success: boolean;
  message: string;
  rewards?: {
    infinite_light?: number;
    infinite_shadow?: number;
    xp?: number;
    conscience?: number;
    social?: number;
  };
  penalties?: {
    police_risk?: number;
    heat?: number;
  };
  data?: Record<string, any>;
}

// Lazy repository accessors
const playerRepo = () => AppDataSource.getRepository(Player);
const healthRepo = () => AppDataSource.getRepository(PlayerHealth);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const gaugesRepo = () => AppDataSource.getRepository(PlayerGauges);
const skillsRepo = () => AppDataSource.getRepository(PlayerSkills);
const gangMemberRepo = () => AppDataSource.getRepository(GangMember);

export class MapActionService {

  private static clamp(n: number, min: number, max: number): number {
    return Math.max(min, Math.min(max, n));
  }

  /** +15% success bonus at night (20h-6h Paris time) */
  private static getNightBonus(): number {
    const now = new Date();
    const month = now.getUTCMonth();
    const offset = (month >= 2 && month <= 9) ? 2 : 1; // Paris DST
    const hour = (now.getUTCHours() + offset) % 24;
    return (hour >= 20 || hour < 6) ? 1.15 : 1.0;
  }

  private static async getSkills(playerId: string): Promise<Map<number, number>> {
    const skills = await skillsRepo().find({ where: { player_id: playerId } });
    const map = new Map<number, number>();
    for (const s of skills) map.set(s.skill_id, s.level);
    return map;
  }

  private static getSkill(skills: Map<number, number>, skillId: number): number {
    return skills.get(skillId) ?? 0;
  }

  private static async applyGaugeDeltas(playerId: string, deltas: Partial<Record<keyof PlayerGauges, number>>) {
    // Phase 16 (2026-04-22) — si `chaleur` présent dans les deltas, on le
    // route via HeatService (source unique U4) pour conserver le trail
    // HeatEvent. Les autres gauges restent gérées en SQL direct.
    const chaleurDelta = Number(deltas.chaleur ?? 0);
    if (chaleurDelta !== 0 && Number.isFinite(chaleurDelta)) {
      const { HeatService } = await import('./heat.service');
      await HeatService.applyToPlayer(playerId, chaleurDelta, 'map_action_gauge', 'map-action');
    }

    const qb = gaugesRepo().createQueryBuilder().update();
    const set: Record<string, () => string> = {};
    for (const [k, v] of Object.entries(deltas)) {
      if (k === 'chaleur') continue; // déjà géré par HeatService
      const delta = Number(v);
      if (!Number.isFinite(delta) || delta === 0) continue;
      const col = k;
      const deltaSql = delta.toFixed(1);
      set[col] = () => `LEAST(100, GREATEST(0, ${col} + ${deltaSql}))`;
    }

    const keys = Object.keys(set);
    if (keys.length === 0) return;

    await qb.set(set).where('player_id = :pid', { pid: playerId }).execute();
  }

  /**
   * FIX(audit-15-04): Self-target guard — prevents exploits like
   * burgling your own residence or extorting your own business.
   * Returns an error ActionResult if the target is owned by the player, null otherwise.
   */
  private static async checkNotSelfTargeting(
    playerId: string,
    targetType: string,
    targetId: string,
    verb: string,
  ): Promise<ActionResult | null> {
    if (targetType === 'player' || targetType === 'npc') {
      if (targetId === playerId) {
        return { success: false, message: `Impossible de vous ${verb} vous-meme` };
      }
      return null;
    }
    try {
      if (targetType === 'business') {
        const { Business } = await import('../models/Business');
        const b = await AppDataSource.getRepository(Business).findOne({ where: { id: targetId } });
        if (!b) return { success: false, message: 'Commerce introuvable' };
        if (b.player_id === playerId) {
          return { success: false, message: `Impossible de ${verb} votre propre commerce` };
        }
      } else if (targetType === 'residence') {
        const { Residence } = await import('../models/Residence');
        const r = await AppDataSource.getRepository(Residence).findOne({ where: { id: targetId } });
        if (!r) return { success: false, message: 'Residence introuvable' };
        if (r.player_id === playerId) {
          return { success: false, message: `Impossible de ${verb} votre propre residence` };
        }
      } else if (targetType === 'warehouse') {
        const { Warehouse } = await import('../models/Warehouse');
        const w = await AppDataSource.getRepository(Warehouse).findOne({ where: { id: targetId } });
        if (!w) return { success: false, message: 'Entrepot introuvable' };
        if (w.player_id === playerId) {
          return { success: false, message: `Impossible de ${verb} votre propre entrepot` };
        }
      }
    } catch (err) {
      return { success: false, message: `Erreur de validation: ${(err as Error).message}` };
    }
    return null;
  }

  /**
   * Get available actions for a target
   */
  /**
   * audit 15-04-2026 Phase 9 : mapping icon -> infra_type pour les POIs orphelins.
   * Duplique la table de map-action.routes.ts (extraction en constants/infra.ts possible
   * si l'usage grandit).
   */
  private static readonly INFRA_ICON_MAP: Record<string, string> = {
    'police': 'police_station',
    'city-hall': 'town_hall',
    'gavel': 'courthouse',
    'hospital': 'hospital',
    'pharmacy': 'pharmacy',
    'bank': 'bank',
    'mail': 'post_office',
    'exchange': 'exchange_office',
  };

  /** Derive infra_type from a POI row (uses icon field). Returns null si non-infrastructure. */
  private static async resolveInfraType(targetType: string, targetId: string): Promise<string | null> {
    if (targetType !== 'infrastructure') return null;
    const { POI } = await import('../models/POI');
    const poi = await AppDataSource.getRepository(POI).findOne({ where: { id: targetId } });
    if (!poi || !poi.icon) return null;
    return MapActionService.INFRA_ICON_MAP[poi.icon] ?? null;
  }

  /**
   * Phase 17.2 finition Gap 6 (2026-05-06) — Résout le player_id du
   * propriétaire de la cible selon son type. Utilisé par le check
   * non-aggression cartel pour identifier la victime potentielle.
   *
   * Mapping :
   *   • 'player' / 'npc'        → targetId est déjà le player_id
   *   • 'residence'             → Residence.player_id
   *   • 'business' / 'warehouse' → table.player_id
   *   • 'vehicle'               → Vehicle.player_id
   *   • 'infrastructure'        → null (pas de propriétaire joueur)
   */
  private static async resolveTargetPlayerId(
    targetType: string,
    targetId: string,
  ): Promise<string | null> {
    if (targetType === 'player' || targetType === 'npc') return targetId;

    if (targetType === 'residence') {
      const { Residence } = await import('../models/Residence');
      const r = await AppDataSource.getRepository(Residence).findOne({
        where: { id: targetId },
        select: ['id', 'player_id'],
      });
      return r?.player_id ?? null;
    }

    if (targetType === 'business') {
      const { Business } = await import('../models/Business');
      const b = await AppDataSource.getRepository(Business).findOne({
        where: { id: targetId },
        select: ['id', 'player_id'],
      });
      return b?.player_id ?? null;
    }

    if (targetType === 'warehouse') {
      const { Warehouse } = await import('../models/Warehouse');
      const w = await AppDataSource.getRepository(Warehouse).findOne({
        where: { id: targetId },
        select: ['id', 'player_id'],
      });
      return w?.player_id ?? null;
    }

    if (targetType === 'vehicle') {
      const { Vehicle } = await import('../models/Vehicle');
      const v = await AppDataSource.getRepository(Vehicle).findOne({
        where: { id: targetId },
        select: ['id', 'player_id'],
      });
      return v?.player_id ?? null;
    }

    return null;
  }

  static async getAvailableActions(
    playerId: string,
    targetType: string,
    targetId: string,
  ): Promise<MapAction[]> {
    const player = await playerRepo().findOne({ where: { id: playerId } });
    if (!player) return [];

    const playerGang = await gangMemberRepo().findOne({
      where: { player_id: playerId },
    });
    const hasGang = !!playerGang;

    // audit 15-04-2026 Phase 9 : si cible = infrastructure, derive infra_type pour filtrage
    const infraType = await MapActionService.resolveInfraType(targetType, targetId);

    // audit 15-04-2026 feedback : detecte si le business cible est une armurerie
    // (pour exposer l'action 'buy_weapon' uniquement sur les armureries).
    let businessType: string | null = null;
    if (targetType === 'business') {
      const { Business } = await import('../models/Business');
      const biz = await AppDataSource.getRepository(Business).findOne({ where: { id: targetId } });
      businessType = biz?.type ?? null;
    }

    return MAP_ACTIONS.filter((action) => {
      // 1. Target type must match
      if (!action.targets.includes(targetType as any)) return false;
      // 2. Gang requirement
      if (action.requires_gang && !hasGang) return false;
      // 3. Criminal tier requirement
      if (action.min_criminal_tier > player.criminal_tier) return false;
      // 4. Phase 9 : si infra_types defini, match contre l'infra_type du POI
      if (action.infra_types && action.infra_types.length > 0) {
        if (!infraType) return false;
        if (!action.infra_types.includes(infraType as any)) return false;
      }
      // 5. audit 15-04-2026 feedback : 'buy_weapon' uniquement sur les armureries.
      if (action.code === 'buy_weapon' && businessType !== 'armurerie') return false;
      // Phase 3 (2026-04-20) — actions véhicules filtrées par type business
      if (action.code === 'repair_vehicle' && businessType !== 'garage') return false;
      if (action.code === 'paint_vehicle' && businessType !== 'carrosserie') return false;
      if (action.code === 'buy_vehicle_dealership' && businessType !== 'concessionnaire') return false;
      if (action.code === 'change_style' && businessType !== 'coiffeur') return false;
      // Phase 5 (2026-04-20) — don association : uniquement sur les 3 types associations
      if (action.code === 'donate_association'
          && businessType !== 'association_caritative'
          && businessType !== 'association_ecologique'
          && businessType !== 'association_sociale') return false;
      // Phase 7 (2026-04-20) — méditation : uniquement si POI icon='place_of_worship'
      if (action.code === 'meditate') {
        // targetType doit être 'infrastructure' ET poi.icon='place_of_worship'
        // On résout ici via POI repo (lazy, 1 query)
        return true; // check détaillé fait au handler (optimisation : filtre au niveau poiDetails)
      }
      return true;
    });
  }

  /**
   * Execute an action
   */
  static async executeAction(
    playerId: string,
    actionCode: string,
    targetId: string,
    targetType: string,
    params?: any,
  ): Promise<ActionResult> {
    const action = MAP_ACTIONS.find((a) => a.code === actionCode);
    if (!action) {
      return { success: false, message: 'Action not found' };
    }

    const player = await playerRepo().findOne({ where: { id: playerId } });
    if (!player) {
      return { success: false, message: 'Player not found' };
    }

    // Check hospitalisation / emprisonnement — aucune action sur la carte
    const health = await healthRepo().findOneBy({ player_id: playerId });
    if (health?.isHospitalized) {
      return { success: false, message: 'Vous êtes hospitalisé. Aucune action possible sur la carte.' };
    }
    if (health?.isImprisoned) {
      return { success: false, message: 'Vous êtes incarcéré. Aucune action possible sur la carte.' };
    }

    // Phase 7 (2026-04-20) — méditation bloquante (sauf l'action meditate elle-même n'est pas bloquée avant le set)
    if (actionCode !== 'meditate' && player.meditating_until && new Date(player.meditating_until) > new Date()) {
      return { success: false, message: 'Vous êtes en méditation. Aucune action possible avant la fin.' };
    }

    // Phase 12 (2026-04-20) — vacances bloquante (toutes actions sauf resume côté route)
    if (player.on_vacation_until && new Date(player.on_vacation_until) > new Date()) {
      return { success: false, message: 'Vous êtes en vacances. Compte en pause jusqu\'au ' + new Date(player.on_vacation_until).toLocaleString('fr-FR') + '.' };
    }

    // Phase 12 — protection immunité côté cible : attaque contre joueur en vacances refusée
    if (['assassinate', 'rob_person', 'burgle_residence'].includes(actionCode)) {
      const { VacationService } = await import('./vacation.service');
      const targetOnVacation = targetType === 'player' && await VacationService.isOnVacation(targetId);
      if (targetOnVacation) {
        return { success: false, message: 'Cette cible est en vacances (immunité 72h).' };
      }
    }

    // Phase 17.2 finition Gap 6 (2026-05-06) — Pacte de non-aggression cartel.
    // Si le joueur ET la cible appartiennent à des cartels alliés (status=accepted),
    // toutes les actions agressives sont rejetées. Définition du pacte =
    // contraignante : alliance vaut alors quelque chose en gameplay militaire.
    const AGGRESSIVE_ACTIONS = new Set([
      'assassinate', 'rob_person', 'burgle_residence',
      'extort', 'rob_business', 'sabotage',
      'steal_vehicle',
    ]);
    if (AGGRESSIVE_ACTIONS.has(actionCode)) {
      const targetPlayerId = await MapActionService.resolveTargetPlayerId(targetType, targetId);
      if (targetPlayerId && targetPlayerId !== playerId) {
        const { CartelAllianceService } = await import('./cartel-alliance.service');
        const allied = await CartelAllianceService.arePlayersInAlliedCartels(playerId, targetPlayerId);
        if (allied) {
          return {
            success: false,
            message: 'Vos cartels sont alliés — pacte de non-aggression actif. Cette action est refusée.',
          };
        }
      }
    }

    // Check if player has the action available
    const available = await MapActionService.getAvailableActions(playerId, targetType, targetId);
    if (!available.find((a) => a.code === actionCode)) {
      return { success: false, message: 'Action not available for you' };
    }

    // Dispatch to specific action handler
    let result: ActionResult;
    switch (actionCode) {
      case 'donate':
        result = await MapActionService.executeDonation(playerId, targetId, params?.amount || 0); break;
      case 'assassinate':
        result = await MapActionService.executeAssassination(playerId, targetId); break;
      case 'rob_person':
        result = await MapActionService.executeRobbery(playerId, targetId); break;
      case 'burgle_residence':
        result = await MapActionService.executeBurglary(playerId, targetId); break;
      case 'visit':
        result = await MapActionService.executeVisit(playerId, targetId, targetType); break;
      case 'extort':
        result = await MapActionService.executeExtortion(playerId, targetId); break;
      case 'rob_business':
        result = await MapActionService.executeBusinessRobbery(playerId, targetId); break;
      case 'sabotage':
        result = await MapActionService.executeSabotage(playerId, targetId); break;
      case 'trade':
        result = { success: true, message: 'Ouvrez le marketplace pour echanger avec ce joueur.', data: { redirect: 'marketplace', targetPlayerId: targetId } }; break;
      case 'recruit':
        result = await MapActionService.executeRecruit(playerId, targetId); break;
      case 'enter_vehicle':
        result = await MapActionService.executeEnterVehicle(playerId, targetId); break;
      // ─── Phase 8.12 (2026-04-29) — Carjacking contextuel via MapContextMenu ───
      case 'steal_vehicle':
        result = await MapActionService.executeStealVehicle(playerId, targetId); break;
      // ─── Infrastructure handlers (Phase 9) ───
      case 'heal':
        result = await MapActionService.executeHeal(playerId); break;
      case 'check_record':
        result = await MapActionService.executeCheckRecord(playerId); break;
      case 'pay_bail':
        result = await MapActionService.executePayBail(playerId); break;
      // ─── Armurerie handler (audit 15-04-2026 feedback) ───
      case 'buy_weapon':
        result = await MapActionService.executeBuyWeapon(playerId, targetId, params?.weapon_name); break;
      // ─── Phase 3 (2026-04-20) — Véhicules POIs ───
      case 'repair_vehicle':
        result = await MapActionService.executeRepairVehicle(playerId, targetId, params?.vehicle_id, params?.hp_to_repair); break;
      case 'paint_vehicle':
        result = await MapActionService.executePaintVehicle(playerId, targetId, params?.vehicle_id, params?.heat_reduction); break;
      case 'buy_vehicle_dealership':
        result = await MapActionService.executeBuyVehicleDealership(playerId, targetId, params?.stock_id); break;
      // ─── Phase 7 (2026-04-20) — Méditation lieu de culte ───
      case 'meditate':
        result = await MapActionService.executeMeditate(playerId, targetId); break;
      // ─── Phase 5 (2026-04-20) — Don à association ───
      case 'donate_association':
        result = await MapActionService.executeDonateAssociation(playerId, targetId, params?.heat_reduction); break;
      // ─── Phase 16 (2026-04-21) — Coiffeur change style ───
      case 'change_style':
        result = await MapActionService.executeChangeStyle(playerId, targetId); break;
      // ─── Phase 17 Phase 6 (2026-05-04) — Recrutement spécialistes via POI ───
      // Pas de side-effect serveur ici : on retourne un signal pour que
      // le frontend ouvre le modal SpecialistRecruitLightbox qui fera
      // le hire effectif via /api/specialists/hire (avec daily_rate négocié).
      case 'recruit_lawyer':
        result = { success: true, message: 'Sélectionne un avocat dans la liste.', data: { open_modal: 'recruit_specialist', role: 'lawyer' } }; break;
      case 'recruit_detective':
        result = { success: true, message: 'Sélectionne un enquêteur dans la liste.', data: { open_modal: 'recruit_specialist', role: 'detective' } }; break;
      case 'recruit_medic':
        result = { success: true, message: 'Sélectionne un médecin perso dans la liste.', data: { open_modal: 'recruit_specialist', role: 'medic' } }; break;
      case 'recruit_accountant':
        result = { success: true, message: 'Sélectionne un comptable dans la liste.', data: { open_modal: 'recruit_specialist', role: 'accountant' } }; break;
      default:
        return { success: false, message: `Action "${action.label}" non implementee` };
    }

    // Bug fix (2026-04-29) — actions criminelles : register le crime DANS LES
    // DEUX CAS (succès + échec). Avant, seul le succès registre. Mais quand un
    // cambriolage / extorsion / etc. échoue avec "caught by police", c'est
    // précisément le moment où le criminal_record + flow Phase 7 doivent se
    // déclencher (sinon arrestation invisible côté joueur, GIGN pas alerté,
    // chaleur seule ne fait rien).
    const CRIMINAL_ACTION_CODES = new Set([
      'burgle_residence', 'rob_person', 'rob_business',
      'extort', 'sabotage', 'assassinate',
    ]);
    const isCriminalAction = CRIMINAL_ACTION_CODES.has(actionCode);

    if (action.police_risk > 0 && (result.success || isCriminalAction)) {
      // Roll vs police_risk pour déclencher l'arrestation
      const policeRoll = Math.random() * 100;
      // Sur échec d'action criminelle, on force le check (pas de roll skip) :
      // l'échec = "caught by police", la police est forcément sur place.
      const shouldArrest = !result.success && isCriminalAction
        ? true
        : policeRoll < action.police_risk;

      if (shouldArrest) {
        try {
          const { JudicialService } = await import('./judicial.service');
          const crimeType = actionCode === 'assassinate' ? 'meurtre'
            : actionCode === 'rob_person' ? 'vol'
            : actionCode === 'burgle_residence' ? 'vol'
            : actionCode === 'rob_business' ? 'braquage'
            : actionCode === 'extort' ? 'racket'
            : actionCode === 'sabotage' ? 'fraude'
            : 'vol';
          // Sur échec, arrest_probability plus élevée (0.85 vs 0.6) — le crime
          // est foiré, la police est sur le lieu, l'arrestation est plus probable.
          const arrestProbability = !result.success && isCriminalAction ? 0.85 : 0.6;
          await JudicialService.registerCrimeAndMaybeConvict(playerId, {
            crime_type: crimeType as any,
            description: !result.success && isCriminalAction
              ? `Echec ${action.label} : interpelle sur les lieux`
              : `Interpellation suite a: ${action.label}`,
            is_violent: ['assassinate', 'rob_business'].includes(actionCode),
            arrest_probability: arrestProbability,
            police_risk: action.police_risk,
          });
          result.message += !result.success
            ? ' — Police sur place !'
            : ' — Interpelle par la police !';
          result.penalties = { ...result.penalties, police_risk: action.police_risk };
        } catch (err) {
          console.error('[MAP-ACTION] Police arrest failed:', (err as Error).message);
        }
      }
    }

    // Alert nearby police patrols when a crime is committed
    if (action.police_risk > 0 && result.success && player.current_lat && player.current_lon) {
      try {
        const { PolicePatrolService } = await import('./police-patrol.service');
        const crimeType = actionCode === 'assassinate' ? 'meurtre'
          : actionCode === 'rob_person' ? 'vol'
          : actionCode === 'extort' ? 'racket'
          : actionCode === 'rob_business' ? 'braquage'
          : actionCode === 'sabotage' ? 'fraude'
          : actionCode === 'burgle_residence' ? 'vol'
          : 'vol';
        await PolicePatrolService.detectCrime(
          Number(player.current_lat),
          Number(player.current_lon),
          crimeType,
        );
      } catch (err) {
        console.error('[MAP-ACTION] Police detect failed:', (err as Error).message);
      }
    }

    return result;
  }

  /**
   * Execute donation
   */
  static async executeDonation(playerId: string, targetId: string, amount: number): Promise<ActionResult> {
    const player = await playerRepo().findOne({ where: { id: playerId } });
    if (!player) return { success: false, message: 'Player not found' };

    if (amount < DONATION_RULES.min_amount) {
      return {
        success: false,
        message: `Donation minimum: ${DONATION_RULES.min_amount} ∞`,
      };
    }

    const conscienceBonus = DONATION_RULES.conscience_per_don;

    const socialBonusCount = Math.floor(amount / DONATION_RULES.social_threshold);
    const socialBonus = socialBonusCount * DONATION_RULES.social_per_palier;

    const balances = await balancesRepo().findOne({ where: { player_id: playerId } });
    if (!balances || balances.infinite_light < amount) {
      return { success: false, message: 'Fonds insuffisants' };
    }

    balances.infinite_light -= amount;
    await balancesRepo().save(balances);
    await TransactionService.log({
      player_id: playerId,
      category: 'donation',
      type: 'out',
      amount,
      currency: 'infinite_light',
      description: `Don`,
    });
    await MapActionService.applyGaugeDeltas(playerId, { conscience: conscienceBonus, social: socialBonus } as any);

    return {
      success: true,
      message: `Don de ${amount} ∞ effectué!`,
      rewards: {
        infinite_light: -amount,
        conscience: conscienceBonus,
        social: socialBonus,
      },
    };
  }

  /**
   * Execute assassination
   */
  static async executeAssassination(playerId: string, targetId: string): Promise<ActionResult> {
    const player = await playerRepo().findOne({ where: { id: playerId } });
    const target = await playerRepo().findOne({ where: { id: targetId } });

    if (!player || !target) {
      return { success: false, message: 'Player or target not found' };
    }

    if (player.current_lat === null || player.current_lon === null) {
      return { success: false, message: 'Your position is unknown' };
    }

    if (target.current_lat === null || target.current_lon === null) {
      return { success: false, message: 'Target not found' };
    }

    // Check if in range
    const inRange = VisibilityService.isInRange(
      player.current_lat as number,
      player.current_lon as number,
      target.current_lat as number,
      target.current_lon as number,
      player.influence_radius_m / 1000,
    );

    if (!inRange) {
      return { success: false, message: 'Target not in range' };
    }

    const skills = await MapActionService.getSkills(playerId);
    const combat = MapActionService.getSkill(skills, 1);
    const discretion = MapActionService.getSkill(skills, 2);
    const strategie = MapActionService.getSkill(skills, 10);
    const renseignement = MapActionService.getSkill(skills, 16);

    // Weapon bonus: find best weapon in player inventory
    const weaponBonus = await MapActionService.getBestWeaponBonus(playerId);

    const successRate = MapActionService.clamp(
      (30 + combat * 0.25 + discretion * 0.25 + strategie * 0.15 + renseignement * 0.15 + weaponBonus * 0.3) * MapActionService.getNightBonus(),
      10,
      95,
    );
    const targetGangsters = await gangMemberRepo().find({
      where: { player_id: targetId },
    });

    // Gangsters NOT assigned to guarding a building are FREE to defend their boss
    const freeDefenders = targetGangsters.filter((g) => g.guarding_building_id === null);
    const hasDefense = freeDefenders.length > 0;

    // Defense reduces success rate: each free defender reduces by 8%, capped at -40%
    let finalSuccessRate = successRate;
    if (hasDefense) {
      const defenseReduction = Math.min(freeDefenders.length * 8, 40);
      finalSuccessRate = MapActionService.clamp(successRate - defenseReduction, 5, 95);
    }
    const finalSuccess = Math.random() * 100 < finalSuccessRate;

    // Apply damage to target on success
    if (finalSuccess) {
      const targetHealth = await healthRepo().findOneBy({ player_id: targetId });
      if (targetHealth) {
        const damage = Math.floor(Math.random() * 41) + 40 + Math.floor(weaponBonus * 0.5); // 40-80 + weapon bonus
        const newHp = Math.max(0, targetHealth.physical_health - damage);
        // Phase 8.5d.3 (2026-05-01) — setHp sync BOTH physical_health + sante_physique
        // (corrige bug désync où le combat baissait PV interne sans toucher la jauge UI).
        await HealthService.setHp(targetId, newHp);
        if (newHp <= 0) {
          await healthRepo().update(
            { player_id: targetId },
            { hospitalized_until: new Date(Date.now() + 24 * 60 * 60 * 1000) },
          );
        }
      }
    }

    if (!hasDefense) {
      return {
        success: finalSuccess,
        message: finalSuccess ? `${target.username} a été neutralisé` : 'Échec: la cible vous échappe',
        penalties: { police_risk: 60 },
      };
    }

    return {
      success: finalSuccess,
      message: finalSuccess
        ? `Assassinat réussi malgré ${freeDefenders.length} garde(s)`
        : `Assassinat raté — ${freeDefenders.length} garde(s) ont repoussé l'attaque`,
      penalties: { police_risk: 75 }, // Higher risk when guards are involved
    };
  }

  /**
   * Execute robbery
   */
  static async executeRobbery(playerId: string, targetId: string): Promise<ActionResult> {
    // FIX(audit-15-04): self-target guard
    const selfCheck = await MapActionService.checkNotSelfTargeting(playerId, 'player', targetId, 'voler');
    if (selfCheck) return selfCheck;

    const player = await playerRepo().findOne({ where: { id: playerId } });
    const target = await playerRepo().findOne({ where: { id: targetId } });

    if (!player || !target) {
      return { success: false, message: 'Player or target not found' };
    }

    const skills = await MapActionService.getSkills(playerId);
    const combat = MapActionService.getSkill(skills, 1);
    const intimidation = MapActionService.getSkill(skills, 7);
    const endurance = MapActionService.getSkill(skills, 4);

    const successRate = MapActionService.clamp(
      (40 + combat * 0.3 + intimidation * 0.2 + endurance * 0.1) * MapActionService.getNightBonus(),
      25,
      95,
    );
    const success = Math.random() * 100 < successRate;

    if (success) {
      const targetBalances = await balancesRepo().findOne({ where: { player_id: targetId } });
      const targetWealth = (targetBalances?.infinite_light ?? 0) + (targetBalances?.infinite_shadow ?? 0);
      const pct = (Math.random() * 10 + 5) / 100; // 5-15%
      const loot = Math.min(10000, Math.max(100, Math.floor(targetWealth * pct)));
      await balancesRepo().increment({ player_id: playerId }, 'infinite_shadow', loot);
      await TransactionService.log({
        player_id: playerId,
        category: 'crime',
        type: 'in',
        amount: loot,
        currency: 'infinite_shadow',
        description: `Vol à main armée`,
      });
      await MapActionService.applyGaugeDeltas(playerId, { chaleur: 7, conscience: -3 } as any);
      return {
        success: true,
        message: `Successfully robbed ${target.username} for ${loot} ∞`,
        rewards: { infinite_shadow: loot },
        penalties: { police_risk: 20 },
      };
    }

    await MapActionService.applyGaugeDeltas(playerId, { chaleur: 3, conscience: -1 } as any);

    return {
      success: false,
      message: `Failed to rob ${target.username}`,
      penalties: { police_risk: 10 },
    };
  }

  /**
   * Execute burglary
   */
  static async executeBurglary(playerId: string, targetId: string): Promise<ActionResult> {
    // FIX(audit-15-04): residence lookup + self-target guard.
    // Previously no validation at all — any uuid would roll for loot.
    const selfCheck = await MapActionService.checkNotSelfTargeting(playerId, 'residence', targetId, 'cambrioler');
    if (selfCheck) return selfCheck;

    const skills = await MapActionService.getSkills(playerId);
    const discretion = MapActionService.getSkill(skills, 2);
    const technologie = MapActionService.getSkill(skills, 9);
    const strategie = MapActionService.getSkill(skills, 10);

    const successRate = MapActionService.clamp(
      (30 + discretion * 0.35 + technologie * 0.15 + strategie * 0.1) * MapActionService.getNightBonus(),
      25,
      95,
    );
    const success = Math.random() * 100 < successRate;

    if (success) {
      const loot = Math.floor(Math.random() * 10000) + 2000;
      await balancesRepo().increment({ player_id: playerId }, 'infinite_shadow', loot);
      await TransactionService.log({
        player_id: playerId,
        category: 'crime',
        type: 'in',
        amount: loot,
        currency: 'infinite_shadow',
        description: `Cambriolage`,
      });
      await MapActionService.applyGaugeDeltas(playerId, { chaleur: 9, conscience: -1 } as any);
      return {
        success: true,
        message: 'Residence successfully burgled',
        rewards: { infinite_shadow: loot },
        penalties: { police_risk: 35 },
      };
    }

    await MapActionService.applyGaugeDeltas(playerId, { chaleur: 5 } as any);
    return {
      success: false,
      message: 'Burglary failed - caught by police',
      penalties: { police_risk: 50 },
    };
  }

  // ─── Visit: show building details ──────────────────────────
  static async executeVisit(playerId: string, targetId: string, targetType: string): Promise<ActionResult> {
    const { Business } = await import('../models/Business');
    const { Residence } = await import('../models/Residence');
    const { Warehouse } = await import('../models/Warehouse');

    let details: any = null;
    if (targetType === 'business') {
      details = await AppDataSource.getRepository(Business).findOne({ where: { id: targetId } });
    } else if (targetType === 'residence') {
      details = await AppDataSource.getRepository(Residence).findOne({ where: { id: targetId } });
    } else if (targetType === 'warehouse') {
      details = await AppDataSource.getRepository(Warehouse).findOne({ where: { id: targetId } });
    }

    if (!details) return { success: false, message: 'Batiment introuvable' };

    // Add discovered POI
    const player = await playerRepo().findOne({ where: { id: playerId } });
    if (player && !player.discovered_pois?.includes(targetId)) {
      player.discovered_pois = [...(player.discovered_pois || []), targetId];
      await playerRepo().save(player);
    }

    return {
      success: true,
      message: `Visite: ${details.name || details.type}`,
      data: { entity: details, type: targetType },
    };
  }

  // ─── Extortion: take 1 hour's revenue from cash register ──
  static async executeExtortion(playerId: string, targetId: string): Promise<ActionResult> {
    // FIX(audit-15-04): self-target guard (can't extort your own commerce)
    const selfCheck = await MapActionService.checkNotSelfTargeting(playerId, 'business', targetId, 'extorquer');
    if (selfCheck) return selfCheck;

    const { BusinessEconomyService } = await import('./business-economy.service');
    const skills = await MapActionService.getSkills(playerId);
    const intimidation = MapActionService.getSkill(skills, 7);
    const charisme = MapActionService.getSkill(skills, 6);

    const successRate = MapActionService.clamp(
      45 + intimidation * 0.3 + charisme * 0.2,
      30,
      95,
    );
    const success = Math.random() * 100 < successRate;

    if (!success) {
      await MapActionService.applyGaugeDeltas(playerId, { chaleur: 3 } as any);
      return { success: false, message: 'Extorsion echouee — la cible resiste', penalties: { police_risk: 10 } };
    }

    const result = await BusinessEconomyService.extort(playerId, targetId);
    if (!result.success) {
      return { success: false, message: result.message };
    }

    await balancesRepo().increment({ player_id: playerId }, 'infinite_shadow', result.amount);
    await TransactionService.log({
      player_id: playerId, category: 'crime', type: 'in',
      amount: result.amount, currency: 'infinite_shadow',
      description: `Extorsion`,
    });
    await MapActionService.applyGaugeDeltas(playerId, { chaleur: 5, conscience: -1, pouvoir: 1 } as any);

    return {
      success: true,
      message: result.message,
      rewards: { infinite_shadow: result.amount },
      penalties: { police_risk: 15 },
    };
  }

  // ─── Rob Business: empty cash register + close 3h ────────
  static async executeBusinessRobbery(playerId: string, targetId: string): Promise<ActionResult> {
    // FIX(audit-15-04): self-target guard
    const selfCheck = await MapActionService.checkNotSelfTargeting(playerId, 'business', targetId, 'braquer');
    if (selfCheck) return selfCheck;

    const { BusinessEconomyService } = await import('./business-economy.service');
    const skills = await MapActionService.getSkills(playerId);
    const combat = MapActionService.getSkill(skills, 1);
    const weaponBonus = await MapActionService.getBestWeaponBonus(playerId);

    const successRate = MapActionService.clamp(
      35 + combat * 0.3 + weaponBonus * 0.2,
      20,
      90,
    );
    const success = Math.random() * 100 < successRate;

    if (!success) {
      await MapActionService.applyGaugeDeltas(playerId, { chaleur: 10 } as any);
      return { success: false, message: 'Braquage echoue', penalties: { police_risk: 60 } };
    }

    const result = await BusinessEconomyService.rob(playerId, targetId);
    if (!result.success) {
      return { success: false, message: result.message };
    }

    await balancesRepo().increment({ player_id: playerId }, 'infinite_shadow', result.amount);
    await TransactionService.log({
      player_id: playerId, category: 'crime', type: 'in',
      amount: result.amount, currency: 'infinite_shadow',
      description: `Braquage`,
    });
    await MapActionService.applyGaugeDeltas(playerId, { chaleur: 15, respect: 3 } as any);

    return {
      success: true,
      message: result.message,
      rewards: { infinite_shadow: result.amount },
      penalties: { police_risk: 45 },
    };
  }

  // ─── Sabotage: reduce target revenue ──────────────────────
  static async executeSabotage(playerId: string, targetId: string): Promise<ActionResult> {
    const { Business } = await import('../models/Business');
    const biz = await AppDataSource.getRepository(Business).findOne({ where: { id: targetId } });
    if (!biz) return { success: false, message: 'Batiment introuvable' };
    if (biz.player_id === playerId) return { success: false, message: 'Impossible de saboter votre propre business' };

    const successRate = 50;
    const success = Math.random() * 100 < successRate;

    if (success) {
      const revenueLoss = Math.round(biz.revenue_per_day * 0.3);
      biz.revenue_per_day = Math.max(0, biz.revenue_per_day - revenueLoss);
      await AppDataSource.getRepository(Business).save(biz);
      await MapActionService.applyGaugeDeltas(playerId, { chaleur: 8 } as any);
      return { success: true, message: `Sabotage reussi: ${biz.name} perd ${revenueLoss} I/jour`, penalties: { police_risk: 30 } };
    }

    await MapActionService.applyGaugeDeltas(playerId, { chaleur: 5 } as any);
    return { success: false, message: 'Sabotage echoue', penalties: { police_risk: 40 } };
  }

  // ─── Recruit NPC into gang ────────────────────────────────
  /**
   * audit 15-04-2026 Phase 10 : recrutement payant.
   * Coût initial : 2000 ∞_shadow (argent sale — recrutement criminel).
   * Nouveau member start avec loyalty=50 (Phase 2 column).
   */
  static async executeRecruit(playerId: string, targetId: string): Promise<ActionResult> {
    const { GangMember } = await import('../models/GangMember');
    const memberRepo = AppDataSource.getRepository(GangMember);

    // Check player has a gang + authority
    const membership = await memberRepo.findOne({ where: { player_id: playerId } });
    if (!membership) return { success: false, message: 'Vous devez avoir un gang pour recruter' };
    if (membership.role !== 'leader' && membership.role !== 'officer') {
      return { success: false, message: 'Seul le leader ou officier peut recruter' };
    }

    // Check target is NPC and not already in a gang
    const target = await playerRepo().findOne({ where: { id: targetId } });
    if (!target || !target.is_npc) return { success: false, message: 'Cible non recrutable' };

    const existingMembership = await memberRepo.findOne({ where: { player_id: targetId } });
    if (existingMembership) return { success: false, message: 'Ce PNJ appartient deja a un gang' };

    // audit 15-04-2026 Phase 10 : debit ∞_shadow avant creation
    const RECRUITMENT_COST = 2000; // fixed cost en ∞_shadow
    const balances = await balancesRepo().findOne({ where: { player_id: playerId } });
    if (!balances || balances.infinite_shadow < RECRUITMENT_COST) {
      return {
        success: false,
        message: `Fonds insuffisants. Recrutement: ${RECRUITMENT_COST} ∞ Shadow requis.`,
      };
    }
    balances.infinite_shadow -= RECRUITMENT_COST;
    await balancesRepo().save(balances);

    const newMember = memberRepo.create({
      gang_id: membership.gang_id,
      player_id: targetId,
      role: 'member',
      contribution: 0,
      experience: 0,
      grade: 1,
      influence_radius_m: 300,
      join_date: new Date(),
      // Phase 10 : loyalty initiale, paid_at=now (grace period)
      loyalty: 50,
      last_paid_at: new Date(),
      last_mission_at: null,
    } as any);
    await memberRepo.save(newMember);

    await TransactionService.log({
      player_id: playerId,
      category: 'gang',
      type: 'out',
      amount: RECRUITMENT_COST,
      currency: 'infinite_shadow',
      description: `Recrutement gangster : ${target.username}`,
    });

    return {
      success: true,
      message: `${target.username} rejoint votre gang (${RECRUITMENT_COST} ∞ Shadow)`,
      rewards: { infinite_shadow: -RECRUITMENT_COST },
    };
  }

  // ─── Enter Vehicle ────────────────────────────────────────
  static async executeEnterVehicle(playerId: string, targetId: string): Promise<ActionResult> {
    const { Vehicle } = await import('../models/Vehicle');
    const vehicle = await AppDataSource.getRepository(Vehicle).findOne({ where: { id: targetId } });
    if (!vehicle) return { success: false, message: 'Vehicule introuvable' };
    if (vehicle.player_id !== playerId) return { success: false, message: 'Ce vehicule ne vous appartient pas' };
    if (vehicle.in_use) return { success: false, message: 'Vehicule deja en cours d\'utilisation' };

    await playerRepo().update(playerId, { active_vehicle_id: targetId });
    await AppDataSource.getRepository(Vehicle).update(targetId, { in_use: true, driven_by: playerId });

    return { success: true, message: `Vous montez dans ${vehicle.name}`, data: { vehicle } };
  }

  /**
   * Phase 8.12 (2026-04-29) — Vol de véhicule contextuel (MapContextMenu).
   * Délègue à CarjackService.carjack avec validation des règles :
   *   - Pas le sien
   *   - Pas allié de gang/cartel
   *   - Pas police/NPC institutionnel (driven_by null OU player non-NPC police)
   * CarjackService gère le combat éventuel + transfert + notif anonymisée.
   */
  static async executeStealVehicle(playerId: string, targetId: string): Promise<ActionResult> {
    const { Vehicle } = await import('../models/Vehicle');
    const { CarjackService } = await import('./carjack.service');

    const vehicle = await AppDataSource.getRepository(Vehicle).findOne({ where: { id: targetId } });
    if (!vehicle) return { success: false, message: 'Véhicule introuvable' };
    if (vehicle.player_id === playerId) return { success: false, message: 'Vous possédez déjà ce véhicule' };

    // Check pas allié (même gang_id ou cartel_id)
    if (vehicle.player_id) {
      try {
        const { GangMember } = await import('../models/GangMember');
        const { CartelMember } = await import('../models/CartelMember');
        const gmRepo = AppDataSource.getRepository(GangMember);
        const cmRepo = AppDataSource.getRepository(CartelMember);
        const [meGm, ownerGm] = await Promise.all([
          gmRepo.findOne({ where: { player_id: playerId } }),
          gmRepo.findOne({ where: { player_id: vehicle.player_id } }),
        ]);
        if (meGm && ownerGm && meGm.gang_id === ownerGm.gang_id) {
          return { success: false, message: 'Vous ne pouvez pas voler un véhicule de votre gang' };
        }
        if (meGm && ownerGm) {
          const [meCartels, ownerCartels] = await Promise.all([
            cmRepo.find({ where: { gang_id: meGm.gang_id } }),
            cmRepo.find({ where: { gang_id: ownerGm.gang_id } }),
          ]);
          const myCartelIds = new Set(meCartels.map(c => c.cartel_id));
          if (ownerCartels.some(c => myCartelIds.has(c.cartel_id))) {
            return { success: false, message: 'Vous ne pouvez pas voler un véhicule d\'un cartel allié' };
          }
        }
      } catch { /* skip si erreur lookup */ }

      // Check owner pas NPC police
      const owner = await playerRepo().findOne({ where: { id: vehicle.player_id } });
      if (owner?.is_npc && (owner.npc_role === 'police' || owner.npc_role === 'gign')) {
        return { success: false, message: 'Vous ne pouvez pas voler un véhicule de police' };
      }
    }

    const result = await CarjackService.carjack(playerId, targetId);
    return {
      success: result.success,
      message: result.message,
      data: result.vehicle ? { vehicle: result.vehicle, combat: result.combat } : undefined,
    };
  }

  // ─── Weapon bonus from inventory ──────────────────────────
  /** Find the best weapon the player carries and return its attack_bonus */
  private static async getBestWeaponBonus(playerId: string): Promise<number> {
    const weapons = await AppDataSource.getRepository(PlayerInventory).find({
      where: { player_id: playerId, item_type: 'weapon' as any, storage_condition: 'on_person' as any },
    });
    if (weapons.length === 0) return 0;

    let bestBonus = 0;
    for (const w of weapons) {
      const def = findWeapon(w.item_subtype);
      if (def && def.attack_bonus > bestBonus) {
        bestBonus = def.attack_bonus;
      }
    }
    return bestBonus;
  }

  // ══════════════════════════════════════════════════════════════
  // INFRASTRUCTURE HANDLERS (audit 15-04-2026 Phase 9)
  // Pour POIs orphelins : hopital, commissariat, tribunal, mairie
  // ══════════════════════════════════════════════════════════════

  /**
   * Heal : restaure physical_health a 100 + libere d'une hospitalisation en cours.
   *
   * Tarification :
   *   - Soin basique (physical_health < 100)     : 50 ∞_light par HP manquant
   *   - Liberation d'hospitalisation              : +5000 ∞_light (tarif fixe)
   * Paiement en infinite_light (argent blanc — hopital public).
   */
  static async executeHeal(playerId: string): Promise<ActionResult> {
    const health = await healthRepo().findOneBy({ player_id: playerId });
    if (!health) return { success: false, message: 'Etat de sante introuvable' };

    const missingHp = Math.max(0, 100 - (health.physical_health ?? 0));
    const isHospitalized = health.hospitalized_until !== null && health.hospitalized_until > new Date();

    if (missingHp === 0 && !isHospitalized) {
      return { success: false, message: 'Vous etes deja en pleine forme' };
    }

    const healCost = missingHp * 50;
    const hospitalReleaseCost = isHospitalized ? 5000 : 0;
    const totalCost = healCost + hospitalReleaseCost;

    if (totalCost === 0) {
      return { success: false, message: 'Aucun soin necessaire' };
    }

    const balances = await balancesRepo().findOne({ where: { player_id: playerId } });
    if (!balances || balances.infinite_light < totalCost) {
      return {
        success: false,
        message: `Fonds insuffisants. Coût: ${totalCost} ∞ (${missingHp} HP * 50 + ${hospitalReleaseCost} sortie)`,
      };
    }

    // Debit + update health
    balances.infinite_light -= totalCost;
    await balancesRepo().save(balances);

    // Phase 8.5d.3 (2026-05-01) — healToFull sync physical_health + sante_physique
    // + clear hospitalized_until (corrige bug user 2026-05-01 où executeHeal
    // remontait PV interne à 100 mais laissait sante_physique à sa valeur précédente).
    await HealthService.healToFull(playerId);

    await TransactionService.log({
      player_id: playerId,
      category: 'health',
      type: 'out',
      amount: totalCost,
      currency: 'infinite_light',
      description: `Hopital: soin ${missingHp}HP${isHospitalized ? ' + sortie anticipee' : ''}`,
    });

    return {
      success: true,
      message: isHospitalized
        ? `Soigne a 100 HP et libere de l'hopital (coût ${totalCost} ∞)`
        : `Soigne : ${missingHp} HP restaures (coût ${totalCost} ∞)`,
      rewards: { infinite_light: -totalCost },
      data: { previous_hp: 100 - missingHp, new_hp: 100, released_from_hospital: isHospitalized },
    };
  }

  /**
   * Check record : consulte le casier judiciaire du joueur.
   * Informatif, pas de coût, pas d'effet. Retourne les 50 derniers CriminalRecord + degré police.
   */
  static async executeCheckRecord(playerId: string): Promise<ActionResult> {
    const { JudicialService } = await import('./judicial.service');
    const status = await JudicialService.getStatus(playerId);

    return {
      success: true,
      message: `Casier consulte : ${status.records.length} antecedents enregistres`,
      data: {
        file: status.file,
        level: status.level,
        imprisoned_until: status.imprisoned_until,
        records_count: status.records.length,
        records: status.records.slice(0, 10), // Top 10 for display
      },
    };
  }

  /**
   * Pay bail : liberation anticipee de prison contre paiement.
   *
   * Tarification : 1500 ∞_light par heure de peine restante.
   * Exemple : 24h restantes = 36000 ∞.
   * Paiement en infinite_light (argent blanc — caution legale).
   *
   * Note : n'efface PAS les CriminalRecord, libere juste de prison.
   */
  static async executePayBail(playerId: string): Promise<ActionResult> {
    const health = await healthRepo().findOneBy({ player_id: playerId });
    if (!health) return { success: false, message: 'Etat de sante introuvable' };

    if (!health.imprisoned_until || health.imprisoned_until <= new Date()) {
      return { success: false, message: 'Vous n\'etes pas en prison' };
    }

    const remainingMs = health.imprisoned_until.getTime() - Date.now();
    const remainingHours = Math.max(1, Math.ceil(remainingMs / (60 * 60 * 1000)));
    const bailCost = remainingHours * 1500;

    const balances = await balancesRepo().findOne({ where: { player_id: playerId } });
    if (!balances || balances.infinite_light < bailCost) {
      return {
        success: false,
        message: `Caution insuffisante. Coût: ${bailCost} ∞ (${remainingHours}h * 1500)`,
      };
    }

    balances.infinite_light -= bailCost;
    await balancesRepo().save(balances);

    await healthRepo().update(playerId, { imprisoned_until: null });

    await TransactionService.log({
      player_id: playerId,
      category: 'health',
      type: 'out',
      amount: bailCost,
      currency: 'infinite_light',
      description: `Caution : liberation anticipee (${remainingHours}h)`,
    });

    return {
      success: true,
      message: `Caution payee : libere de prison (${bailCost} ∞ pour ${remainingHours}h)`,
      rewards: { infinite_light: -bailCost },
      data: { remaining_hours: remainingHours, bail_cost: bailCost },
    };
  }

  // ══════════════════════════════════════════════════════════════
  // ARMURERIE HANDLER (audit 15-04-2026, feedback utilisateur)
  // Achat d'arme legale chez une armurerie (business.type='armurerie').
  // Requiert l'item document "Permis de port d'armes" en inventaire.
  // L'action est filtree dans getAvailableActions pour n'etre exposee
  // que sur les businesses de type armurerie.
  // ══════════════════════════════════════════════════════════════

  /**
   * Item_subtype exact utilise dans player_inventory pour le permis de port d'armes.
   * Garde en dur pour eviter les divergences avec les seeds / admin panel.
   */
  private static readonly WEAPON_PERMIT_SUBTYPE = "Permis de port d'armes";

  /**
   * Verifie si le joueur possede un Permis de port d'armes en inventaire.
   * Toute quantite > 0 et tout storage_condition valent possession.
   */
  static async hasWeaponPermit(playerId: string): Promise<boolean> {
    const invRepo = AppDataSource.getRepository(PlayerInventory);
    const row = await invRepo.findOne({
      where: {
        player_id: playerId,
        item_type: 'document',
        item_subtype: MapActionService.WEAPON_PERMIT_SUBTYPE,
      },
    });
    return !!row && row.quantity > 0;
  }

  /**
   * Execute l'achat d'une arme legale chez un armurier.
   *
   * Conditions :
   *  - Le business existe, son type = 'armurerie'.
   *  - Le joueur possede l'item document "Permis de port d'armes".
   *  - L'arme existe dans WEAPONS, is_legal=true.
   *  - Solde infinite_light >= prix de l'arme.
   *
   * Effet :
   *  - Debite le prix en infinite_light (argent blanc — achat legal declare).
   *  - Cree une ligne PlayerInventory item_type='weapon' storage_condition='on_person' quantity=1.
   *  - Credite le cash_register de l'armurier (comme un extort negatif : revenu legitime).
   *  - Log TransactionService.
   */
  static async executeBuyWeapon(
    playerId: string,
    businessId: string,
    weaponName?: string,
  ): Promise<ActionResult> {
    if (!weaponName || typeof weaponName !== 'string') {
      return { success: false, message: 'Nom d\'arme requis (params.weapon_name)' };
    }

    // 1. Verifie le permis en amont pour un message clair.
    const hasPermit = await MapActionService.hasWeaponPermit(playerId);
    if (!hasPermit) {
      return {
        success: false,
        message: 'Permis de port d\'armes requis. Obtenez-le a la prefecture ou sur le marche noir.',
      };
    }

    // 2. Verifie que le business est bien une armurerie.
    const { Business } = await import('../models/Business');
    const bizRepo = AppDataSource.getRepository(Business);
    const biz = await bizRepo.findOne({ where: { id: businessId } });
    if (!biz) return { success: false, message: 'Armurerie introuvable' };
    if (biz.type !== 'armurerie') {
      return { success: false, message: 'Ce commerce n\'est pas une armurerie' };
    }
    if (biz.closed_until && new Date() < biz.closed_until) {
      return { success: false, message: 'Armurerie fermee (braquage recent)' };
    }

    // 3. Valide l'arme demandee : elle doit exister dans WEAPONS et etre legale.
    const weapon = findWeapon(weaponName);
    if (!weapon) {
      return { success: false, message: `Arme "${weaponName}" introuvable dans le catalogue` };
    }
    if (!weapon.is_legal) {
      return { success: false, message: `${weapon.name} n'est pas vendue legalement. Marche noir uniquement.` };
    }
    if (weapon.price <= 0) {
      return { success: false, message: `${weapon.name} n'a pas de prix legal configure` };
    }

    // 4. Verifie le solde infinite_light.
    const balances = await balancesRepo().findOne({ where: { player_id: playerId } });
    if (!balances) return { success: false, message: 'Balance introuvable' };
    if (balances.infinite_light < weapon.price) {
      return {
        success: false,
        message: `Fonds insuffisants. Coût: ${weapon.price} ∞ (solde: ${balances.infinite_light})`,
      };
    }

    // 5. Debit + credit du cash_register de l'armurier (revenue legitime).
    balances.infinite_light -= weapon.price;
    await balancesRepo().save(balances);
    biz.cash_register = (biz.cash_register ?? 0) + weapon.price;
    await bizRepo.save(biz);

    // 6. Ajoute l'arme a l'inventaire du joueur (on_person par defaut).
    const invRepo = AppDataSource.getRepository(PlayerInventory);
    const inv = invRepo.create({
      player_id: playerId,
      item_type: 'weapon',
      item_subtype: weapon.name,
      quantity: 1,
      quality: 3,
      storage_condition: 'on_person',
      storage_location_id: null,
      weight_grams: 1000, // approx 1kg par arme de poing — raffinable via WEAPONS plus tard
      is_listed: false,
    });
    await invRepo.save(inv);

    // 7. Log transaction.
    await TransactionService.log({
      player_id: playerId,
      category: 'commerce',
      type: 'out',
      amount: weapon.price,
      currency: 'infinite_light',
      description: `Armurerie: achat ${weapon.name}`,
    });

    return {
      success: true,
      message: `${weapon.name} achete pour ${weapon.price} ∞`,
      rewards: { infinite_light: -weapon.price },
      data: {
        weapon_name: weapon.name,
        price: weapon.price,
        attack_bonus: weapon.attack_bonus,
      },
    };
  }

  // ══════════════════════════════════════════════════════════════
  // PHASE 3 (2026-04-20) — Véhicules : Garage (repair), Carrosserie (paint), Concessionnaire
  // ══════════════════════════════════════════════════════════════

  /**
   * Garage Auto (amenity=car_repair / business.type='garage') : réparer un véhicule.
   * Prix = business.repair_price_per_hp × hp_to_repair.
   * hp_to_repair ∈ [1..(100 - vehicle.condition)].
   */
  static async executeRepairVehicle(
    playerId: string,
    businessId: string,
    vehicleId?: string,
    hpToRepair?: number,
  ): Promise<ActionResult> {
    if (!vehicleId) return { success: false, message: 'vehicle_id requis' };
    const hp = Math.floor(Number(hpToRepair || 0));
    if (hp < 1) return { success: false, message: 'hp_to_repair invalide (≥ 1)' };

    const { Business } = await import('../models/Business');
    const { Vehicle } = await import('../models/Vehicle');
    const bizRepo = AppDataSource.getRepository(Business);
    const vRepo = AppDataSource.getRepository(Vehicle);

    const biz = await bizRepo.findOneBy({ id: businessId });
    if (!biz) return { success: false, message: 'Garage introuvable' };
    if (biz.type !== 'garage') return { success: false, message: 'Ce commerce n\'est pas un garage' };
    if (biz.closed_until && new Date() < biz.closed_until) {
      return { success: false, message: 'Garage fermé temporairement' };
    }

    const vehicle = await vRepo.findOneBy({ id: vehicleId });
    if (!vehicle) return { success: false, message: 'Véhicule introuvable' };
    if (vehicle.player_id !== playerId) return { success: false, message: 'Ce véhicule ne vous appartient pas' };

    const currentCondition = vehicle.condition ?? 100;
    const maxRepair = 100 - currentCondition;
    if (maxRepair <= 0) return { success: false, message: 'Véhicule déjà en parfait état' };
    const effectiveHp = Math.min(hp, maxRepair);

    const pricePerHp = biz.repair_price_per_hp ?? 5;
    const totalCost = effectiveHp * pricePerHp;

    const balances = await balancesRepo().findOne({ where: { player_id: playerId } });
    if (!balances || Number(balances.infinite_light) < totalCost) {
      return { success: false, message: `Fonds insuffisants (${totalCost} ∞ requis)` };
    }

    balances.infinite_light -= totalCost;
    await balancesRepo().save(balances);

    vehicle.condition = Math.min(100, currentCondition + effectiveHp);
    await vRepo.save(vehicle);

    // Crédit cash register du garage
    biz.cash_register = (biz.cash_register ?? 0) + totalCost;
    await bizRepo.save(biz);

    await TransactionService.log({
      player_id: playerId, category: 'commerce', type: 'out',
      amount: totalCost, currency: 'infinite_light',
      description: `Garage : réparation ${effectiveHp} HP (${vehicle.name})`,
    });

    return {
      success: true,
      message: `${effectiveHp} HP réparés sur ${vehicle.name} (${totalCost} ∞)`,
      rewards: { infinite_light: -totalCost },
      data: { vehicle_id: vehicleId, hp_repaired: effectiveHp, new_condition: vehicle.condition },
    };
  }

  /**
   * Carrosserie (shop=perfumery / business.type='carrosserie') : repeindre véhicule.
   * Prix = heat_reduction × 6 000 ∞. Max 10 pts par session. Cooldown 6h/véhicule.
   */
  static async executePaintVehicle(
    playerId: string,
    businessId: string,
    vehicleId?: string,
    heatReduction?: number,
  ): Promise<ActionResult> {
    const PRICE_PER_PT = 6_000;
    const MAX_REDUCTION = 10;
    const COOLDOWN_HOURS = 6;

    if (!vehicleId) return { success: false, message: 'vehicle_id requis' };
    const pts = Math.floor(Number(heatReduction || 0));
    if (pts < 1 || pts > MAX_REDUCTION) {
      return { success: false, message: `heat_reduction ∈ [1..${MAX_REDUCTION}]` };
    }

    const { Business } = await import('../models/Business');
    const { Vehicle } = await import('../models/Vehicle');
    const biz = await AppDataSource.getRepository(Business).findOneBy({ id: businessId });
    if (!biz) return { success: false, message: 'Carrosserie introuvable' };
    if (biz.type !== 'carrosserie') return { success: false, message: 'Ce commerce n\'est pas une carrosserie' };

    const vehicle = await AppDataSource.getRepository(Vehicle).findOneBy({ id: vehicleId });
    if (!vehicle) return { success: false, message: 'Véhicule introuvable' };
    if (vehicle.player_id !== playerId) return { success: false, message: 'Ce véhicule ne vous appartient pas' };

    if (vehicle.last_painted_at) {
      const sinceMs = Date.now() - new Date(vehicle.last_painted_at).getTime();
      const cooldownMs = COOLDOWN_HOURS * 3600 * 1000;
      if (sinceMs < cooldownMs) {
        const remainH = Math.ceil((cooldownMs - sinceMs) / 3600000);
        return { success: false, message: `Véhicule déjà repeint récemment (cooldown ${remainH}h)` };
      }
    }

    const totalCost = pts * PRICE_PER_PT;
    const balances = await balancesRepo().findOne({ where: { player_id: playerId } });
    if (!balances || Number(balances.infinite_light) < totalCost) {
      return { success: false, message: `Fonds insuffisants (${totalCost} ∞ requis)` };
    }

    balances.infinite_light -= totalCost;
    await balancesRepo().save(balances);

    await MapActionService.applyGaugeDeltas(playerId, { chaleur: -pts } as any);
    vehicle.last_painted_at = new Date();
    await AppDataSource.getRepository(Vehicle).save(vehicle);

    biz.cash_register = (biz.cash_register ?? 0) + totalCost;
    await AppDataSource.getRepository(Business).save(biz);

    await TransactionService.log({
      player_id: playerId, category: 'commerce', type: 'out',
      amount: totalCost, currency: 'infinite_light',
      description: `Carrosserie : peinture −${pts} chaleur (${vehicle.name})`,
    });

    // Log heat event (audit trail)
    try {
      const { HeatEventService } = await import('./heat-event.service');
      await HeatEventService.log({
        target_type: 'player', target_id: playerId,
        delta: -pts, new_value: 0,  // computed ailleurs
        reason: 'carrosserie_repaint', source: vehicle.name,
      });
    } catch { /* silent */ }

    return {
      success: true,
      message: `${vehicle.name} repeint (−${pts} chaleur, ${totalCost} ∞)`,
      rewards: { infinite_light: -totalCost },
      data: { vehicle_id: vehicleId, heat_reduction: pts },
    };
  }

  /**
   * Concessionnaire (amenity=car_rental) : achat d'un véhicule depuis le stock hebdo.
   * Délègue à DealershipService.buyVehicle qui gère transaction atomique.
   */
  static async executeBuyVehicleDealership(
    playerId: string,
    poiId: string,
    stockId?: string,
  ): Promise<ActionResult> {
    if (!stockId) return { success: false, message: 'stock_id requis' };

    // Le targetId du POI pointe vers le Dealership via entity_id
    const { POI } = await import('../models/POI');
    const poi = await AppDataSource.getRepository(POI).findOneBy({ id: poiId });
    if (!poi || poi.icon !== 'car_rental' || !poi.entity_id) {
      return { success: false, message: 'Concessionnaire introuvable' };
    }

    const { DealershipService } = await import('./dealership.service');
    try {
      const result = await DealershipService.buyVehicle(playerId, poi.entity_id, stockId);
      return {
        success: true,
        message: `Véhicule acheté (${result.price} ∞)`,
        rewards: { infinite_light: -result.price },
        data: { vehicle_id: result.vehicle_id },
      };
    } catch (err: any) {
      return { success: false, message: err.message || 'Achat refusé' };
    }
  }

  // ══════════════════════════════════════════════════════════════
  // PHASE 7 (2026-04-20) — Méditation lieu de culte (amenity=place_of_worship)
  // ══════════════════════════════════════════════════════════════

  /**
   * Lance une méditation 8h. Bloque toute action pendant la durée.
   * À la fin (CRON 60s), −1 chaleur.
   */
  static async executeMeditate(playerId: string, poiId: string): Promise<ActionResult> {
    const { POI } = await import('../models/POI');
    const poi = await AppDataSource.getRepository(POI).findOneBy({ id: poiId });
    if (!poi || poi.icon !== 'place_of_worship') {
      return { success: false, message: 'Ce lieu n\'est pas un lieu de culte' };
    }
    const { MeditationService } = await import('./meditation.service');
    try {
      const r = await MeditationService.startMeditation(playerId);
      return {
        success: true,
        message: `Méditation commencée. Retour prévu : ${new Date(r.resumes_at).toLocaleString('fr-FR')}`,
        data: { resumes_at: r.resumes_at },
      };
    } catch (err: any) {
      return { success: false, message: err.message };
    }
  }

  // ══════════════════════════════════════════════════════════════
  // PHASE 5 (2026-04-20) — Don à une association (caritative / écolo / sociale)
  // ══════════════════════════════════════════════════════════════

  static async executeDonateAssociation(
    playerId: string,
    businessId: string,
    heatReduction?: number,
  ): Promise<ActionResult> {
    const { AssociationService } = await import('./association.service');
    try {
      const r = await AssociationService.donate(playerId, businessId, Number(heatReduction || 1));
      return {
        success: true,
        message: `Don ${r.association_type.replace('association_', '')} : ${r.amount} ∞ → −${r.heat_reduction} chaleur`,
        rewards: { infinite_light: -r.amount },
        data: r,
      };
    } catch (err: any) {
      return { success: false, message: err.message };
    }
  }

  // ══════════════════════════════════════════════════════════════
  // PHASE 16 (2026-04-21) — Coiffeur : change style = -1 chaleur 1x/sem
  // ══════════════════════════════════════════════════════════════
  static async executeChangeStyle(
    playerId: string,
    _businessId: string,
  ): Promise<ActionResult> {
    const { GameSettingsService } = await import('./game-settings.service');
    const player = await playerRepo().findOneBy({ id: playerId });
    if (!player) return { success: false, message: 'Joueur introuvable' };

    const cost = Number(GameSettingsService.get('coiffeur_change_style_cost', 8000));
    const heatReduction = Number(GameSettingsService.get('coiffeur_change_style_heat', 1));
    const cooldownDays = Number(GameSettingsService.get('coiffeur_change_style_cooldown_days', 7));

    // Check cooldown
    if (player.last_style_change_at) {
      const last = new Date(player.last_style_change_at).getTime();
      const cooldownMs = cooldownDays * 24 * 60 * 60 * 1000;
      if (Date.now() - last < cooldownMs) {
        const remaining = Math.ceil((cooldownMs - (Date.now() - last)) / (24 * 60 * 60 * 1000));
        return { success: false, message: `Vous avez déjà changé de style cette semaine (attendre ${remaining}j).` };
      }
    }

    // Check solde
    const balances = await balancesRepo().findOneBy({ player_id: playerId });
    if (!balances || balances.infinite_light < cost) {
      return { success: false, message: `Solde insuffisant (${cost.toLocaleString('fr-FR')} ∞ requis)` };
    }

    // Débit + application effet
    balances.infinite_light -= cost;
    await balancesRepo().save(balances);

    const gauges = await gaugesRepo().findOneBy({ player_id: playerId });
    if (gauges) {
      const newHeat = Math.max(0, Number(gauges.chaleur) - heatReduction);
      gauges.chaleur = newHeat as any;
      await gaugesRepo().save(gauges);
    }

    player.last_style_change_at = new Date();
    await playerRepo().save(player);

    return {
      success: true,
      message: `Nouveau style adopté. −${heatReduction} chaleur (coût ${cost.toLocaleString('fr-FR')} ∞).`,
      rewards: { infinite_light: -cost },
    };
  }
}



