import { AppDataSource } from '../config/database';
import { Player } from '../models/Player';
import { PlayerHealth } from '../models/PlayerHealth';
import { PlayerGauges } from '../models/PlayerGauges';
import { HealthService } from './health.service';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerSkills } from '../models/PlayerSkills';
import { MissionProgress } from '../models/MissionProgress';
import { Mission } from '../models/Mission';
import { GangMember } from '../models/GangMember';
import { In, IsNull, Not } from 'typeorm';
import {
  PRISON_MECHANICS,
  PRISON_NPC_REDEMPTION,
  PRISON_NPC_CRIME,
  LAWYER_COMPARISON,
  DEAL_MISSION_MECHANICS,
} from '../constants/prison';
import { PlayerInventory } from '../models/PlayerInventory';
import { SKILL_DEFINITIONS } from '../models/PlayerSkills';
import {
  PRISON_MARKET_CHANNELS,
  PRISON_WEAPON_COMBAT_BONUS,
  PRISON_PHONE_RULES,
  type PrisonMarketItem,
} from '../constants/prison-marketplace';
import {
  PRISON_LAYOUT,
  PRISON_FLOORS,
  PRISON_INTERACTION_EFFECTS,
  PRISON_SEARCH_MECHANICS,
  getLocationsByFloor,
  getLocationById,
  type PrisonLocation,
  type PrisonFloor,
  type PrisonInteraction,
} from '../constants/prison-layout';
import { PRISON_CIGARETTE_RESALE } from '../constants/cigarettes';
import { JudicialService } from './judicial.service';

const playerRepo = () => AppDataSource.getRepository(Player);
const healthRepo = () => AppDataSource.getRepository(PlayerHealth);
const gaugesRepo = () => AppDataSource.getRepository(PlayerGauges);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const skillsRepo = () => AppDataSource.getRepository(PlayerSkills);
const missionRepo = () => AppDataSource.getRepository(Mission);
const progressRepo = () => AppDataSource.getRepository(MissionProgress);
const gangMemberRepo = () => AppDataSource.getRepository(GangMember);
const inventoryRepo = () => AppDataSource.getRepository(PlayerInventory);

/** Convertit un nom de skill (ex: 'combat') en skill_id (ex: 1) */
function skillNameToId(name: string): number | null {
  const lower = name.toLowerCase();
  for (const [id, def] of Object.entries(SKILL_DEFINITIONS)) {
    if (def.name.toLowerCase() === lower) return parseInt(id, 10);
  }
  return null;
}

/** Récupère le level d'un skill par son nom pour un joueur */
async function getSkillLevel(playerId: string, skillName: string): Promise<number> {
  const sid = skillNameToId(skillName);
  if (!sid) return 0;
  const skill = await skillsRepo().findOne({
    where: { player_id: playerId, skill_id: sid },
  });
  return skill?.level ?? 0;
}

export type PrisonCursus = 'redemption' | 'crime';

export interface PrisonStatus {
  is_imprisoned: boolean;
  sentence_end: Date | null;
  remaining_hours: number;
  cursus: PrisonCursus | null;
  /**
   * Phase 8 (2026-04-27) — au plus UNE mission visible à la fois (pattern
   * identique au Footer MissionsColumn) : si une mission est in_progress, ce
   * tableau est vide et `mission_in_progress` est rempli ; sinon il contient
   * la 1ʳᵉ mission disponible du cursus.
   */
  available_missions: Mission[];
  /**
   * Phase 8 (2026-04-27) — mission prison actuellement in_progress avec sa
   * relation `.mission` complète (narrative, has_moral_choice, …) afin que le
   * frontend puisse l'afficher dans MissionResultModal sans refetch.
   */
  mission_in_progress: MissionProgress | null;
  completed_missions: string[];
  npc_contacts: typeof PRISON_NPC_REDEMPTION | typeof PRISON_NPC_CRIME | readonly any[];
  access: typeof PRISON_MECHANICS.cursus_access.redemption | typeof PRISON_MECHANICS.cursus_access.crime;
  daily_effects: typeof PRISON_MECHANICS.daily_gauge_effects;
  bras_droit_active: boolean;
  // Phase 8.5 (2026-04-29) — Bâtiment courant + activité (B1 Arrivants /
  // B2 Jungle / B3 Travailleurs ; free / work / study)
  prison_building?: 'B1' | 'B2' | 'B3' | null;
  prison_activity?: 'free' | 'work' | 'study' | null;
  imprisoned_at?: Date | null;
}

export class PrisonService {

  /**
   * Vérifie si le joueur est actuellement en prison et retourne son statut complet
   */
  static async getPrisonStatus(playerId: string): Promise<PrisonStatus> {
    const health = await healthRepo().findOneBy({ player_id: playerId });
    const isImprisoned = health?.isImprisoned ?? false;

    if (!isImprisoned || !health?.imprisoned_until) {
      return {
        is_imprisoned: false,
        sentence_end: null,
        remaining_hours: 0,
        cursus: null,
        available_missions: [],
        mission_in_progress: null,
        completed_missions: [],
        npc_contacts: [] as any[],
        access: PRISON_MECHANICS.cursus_access.redemption,
        daily_effects: PRISON_MECHANICS.daily_gauge_effects,
        bras_droit_active: false,
      };
    }

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

    // Déterminer le cursus choisi (stocké en progression de mission)
    const prisonProgress = await progressRepo()
      .createQueryBuilder('p')
      .leftJoinAndSelect('p.mission', 'm')
      .where('p.player_id = :pid', { pid: playerId })
      .andWhere('m.category = :cat', { cat: 'prison' })
      .getMany();

    let cursus: PrisonCursus | null = null;
    const completedCodes: string[] = [];
    let inProgressEntry: MissionProgress | null = null;

    for (const prog of prisonProgress) {
      if (prog.mission?.code?.startsWith('PR_RE_')) {
        cursus = 'redemption';
      } else if (prog.mission?.code?.startsWith('PR_CR_')) {
        cursus = 'crime';
      }
      if (prog.status === 'completed' && prog.mission?.code) {
        completedCodes.push(prog.mission.code);
      }
      if (prog.status === 'in_progress' && prog.mission?.code) {
        inProgressEntry = prog;
      }
    }

    // Missions disponibles
    const allPrisonMissions = await missionRepo().find({
      where: { category: 'prison' as any, is_active: true },
      order: { order_index: 'ASC' },
    });

    const inProgressCode = inProgressEntry?.mission?.code ?? null;

    // Phase 8 (2026-04-27) — pattern Footer MissionsColumn : 1 seule mission
    // disponible visible à la fois. La mission in_progress est exclue (elle
    // est servie séparément via `mission_in_progress`).
    const availableMissions = allPrisonMissions.filter((m) => {
      if (!cursus) return m.order_index <= 1 || m.order_index === 11; // Première mission de chaque cursus
      if (cursus === 'redemption' && !m.code.startsWith('PR_RE_')) return false;
      if (cursus === 'crime' && !m.code.startsWith('PR_CR_')) return false;
      if (completedCodes.includes(m.code)) return false;
      if (inProgressCode && m.code === inProgressCode) return false;

      // Vérifier les prérequis
      const prereqs = m.prerequisites as any;
      if (prereqs?.missions?.length) {
        return prereqs.missions.every((req: string) => completedCodes.includes(req));
      }
      return true;
    }).slice(0, 1);

    // Bras droit actif ?
    const membership = await gangMemberRepo().findOne({ where: { player_id: playerId } });
    const gangId = membership?.gang_id ?? null;
    const brasDroit = gangId
      ? await gangMemberRepo().findOne({ where: { gang_id: gangId, role: 'bras_droit' as any } })
      : null;
    const brasDroitActive = !!brasDroit && !brasDroit.isHospitalized;

    return {
      is_imprisoned: true,
      sentence_end: health.imprisoned_until,
      remaining_hours: Math.round(remainingHours * 10) / 10,
      cursus,
      available_missions: availableMissions,
      mission_in_progress: inProgressEntry,
      completed_missions: completedCodes,
      npc_contacts: cursus === 'crime' ? PRISON_NPC_CRIME : PRISON_NPC_REDEMPTION,
      access: cursus === 'crime'
        ? PRISON_MECHANICS.cursus_access.crime
        : PRISON_MECHANICS.cursus_access.redemption,
      daily_effects: PRISON_MECHANICS.daily_gauge_effects,
      bras_droit_active: brasDroitActive,
      // Phase 8.5 (2026-04-29) — Bâtiment courant + activité (B1/B2/B3, free/work/study)
      prison_building: (health as any).prison_building ?? 'B1',
      prison_activity: (health as any).prison_activity ?? 'free',
      imprisoned_at: (health as any).imprisoned_at ?? null,
    };
  }

  /**
   * Choisir un cursus prison (une seule fois par incarcération)
   */
  static async chooseCursus(playerId: string, cursus: PrisonCursus): Promise<void> {
    const status = await PrisonService.getPrisonStatus(playerId);
    if (!status.is_imprisoned) throw new Error('Vous n\'êtes pas en prison.');
    if (status.cursus) throw new Error('Vous avez déjà choisi un cursus pour cette incarcération.');

    // Débloquer la première mission du cursus choisi
    const firstCode = cursus === 'redemption' ? 'PR_RE_01' : 'PR_CR_01';
    const mission = await missionRepo().findOneBy({ code: firstCode });
    if (!mission) throw new Error('Mission introuvable. Le seed prison est-il exécuté ?');

    const existing = await progressRepo().findOne({
      where: { player_id: playerId, mission_id: mission.id },
    });

    if (!existing) {
      await progressRepo().save(progressRepo().create({
        player_id: playerId,
        mission_id: mission.id,
        status: 'available',
      }));
    }
  }

  /**
   * Appliquer les effets quotidiens de la prison sur les jauges
   * Appelé par CRON toutes les 24h pour chaque joueur emprisonné
   */
  static async applyDailyPrisonEffects(): Promise<number> {
    const allHealth = await healthRepo().find();
    let affected = 0;

    for (const health of allHealth) {
      if (!health.isImprisoned) continue;

      const effects = PRISON_MECHANICS.daily_gauge_effects;

      // Phase 8 v2 health refactor (2026-05-01) — sante_physique passe via
      // HealthService.adjustHp pour single source physical_health. Les autres
      // jauges (social/respect/chaleur) restent sur player_gauges.
      if (effects.physical_health) {
        await HealthService.adjustHp(health.player_id, effects.physical_health);
      }
      await gaugesRepo()
        .createQueryBuilder()
        .update()
        .set({
          social: () => `GREATEST(0, LEAST(100, social + ${effects.social}))`,
          respect: () => `GREATEST(0, LEAST(100, respect + ${effects.respect}))`,
          chaleur: () => `GREATEST(0, LEAST(100, chaleur + ${effects.chaleur}))`,
        })
        .where('player_id = :pid', { pid: health.player_id })
        .execute();

      // Appliquer sur PlayerHealth
      await healthRepo()
        .createQueryBuilder()
        .update()
        .set({
          mental_health: () => `GREATEST(0, LEAST(100, mental_health + ${effects.mental_health}))`,
          stress: () => `GREATEST(0, LEAST(100, stress + ${effects.stress}))`,
        })
        .where('player_id = :pid', { pid: health.player_id })
        .execute();

      affected++;
    }

    return affected;
  }

  /**
   * Recruter l'avocat 5★ (mission PR_RE_02 choix A)
   */
  static async recruitFiveStarLawyer(playerId: string): Promise<void> {
    const balances = await balancesRepo().findOneBy({ player_id: playerId });
    if (!balances) throw new Error('Joueur introuvable');

    const cost = LAWYER_COMPARISON.five_star.salary_per_day; // Coût initial = 5000
    const recruitCost = 5000;

    if (balances.infinite_light < recruitCost) {
      throw new Error(`Fonds insuffisants. Recrutement: ${recruitCost} ∞ Light requis.`);
    }

    await balancesRepo().decrement({ player_id: playerId }, 'infinite_light', recruitCost);

    // Appliquer réduction de peine (-20%)
    const health = await healthRepo().findOneBy({ player_id: playerId });
    if (health?.imprisoned_until) {
      const remainingMs = health.imprisoned_until.getTime() - Date.now();
      const reducedMs = remainingMs * (1 - LAWYER_COMPARISON.five_star.sentence_reduction_pct / 100);
      const newEnd = new Date(Date.now() + reducedMs);
      await healthRepo().update(health.player_id, { imprisoned_until: newEnd });
    }
  }

  /**
   * Exécuter un Deal (mission empire) — envoyer des gangsters vendre des items
   */
  static async executeDeal(playerId: string, params: {
    gangster_ids: string[];
    items: Array<{ item_type: string; quantity: number; storage_id: string }>;
  }): Promise<{
    success: boolean;
    revenue: number;
    price_multiplier: number;
    gangster_xp: number;
  }> {
    const membership = await gangMemberRepo().findOne({ where: { player_id: playerId } });
    const gangId = membership?.gang_id ?? null;
    if (!gangId) throw new Error('Aucun gang');

    const gangsterIds = Array.isArray(params.gangster_ids) ? params.gangster_ids.filter(Boolean) : [];
    if (gangsterIds.length === 0) throw new Error('Sélectionnez au moins un gangster.');

    const gangsters = await gangMemberRepo().find({
      where: { gang_id: gangId, player_id: In(gangsterIds) },
    });
    if (gangsters.length !== gangsterIds.length) {
      throw new Error('Gangster invalide.');
    }

    for (const g of gangsters) {
      if (!g.isAvailable) throw new Error('Un gangster est indisponible.');
    }

    // Calculer la compétence moyenne pertinente des gangsters assignés
    const relevantSkills = DEAL_MISSION_MECHANICS.relevant_skills;
    let totalSkillAvg = 0;

    for (const g of gangsters) {
      let gSkillSum = 0;
      for (const skillName of relevantSkills) {
        gSkillSum += await getSkillLevel(g.player_id, skillName);
      }
      totalSkillAvg += gSkillSum / relevantSkills.length;
    }

    const avgSkill = gangsters.length > 0 ? totalSkillAvg / gangsters.length : 0;

    // Déterminer le multiplicateur de prix
    let priceMultiplier: number;
    if (avgSkill < DEAL_MISSION_MECHANICS.skill_thresholds.below_average) {
      priceMultiplier = DEAL_MISSION_MECHANICS.price_multiplier.below_average;
    } else if (avgSkill > DEAL_MISSION_MECHANICS.skill_thresholds.above_average) {
      priceMultiplier = DEAL_MISSION_MECHANICS.price_multiplier.above_average;
    } else {
      priceMultiplier = DEAL_MISSION_MECHANICS.price_multiplier.average;
    }

    // Calculer le revenu total (prix du marché * multiplicateur)
    // Le prix de base est déterminé par l'item — ici on retourne le multiplicateur
    // Le calcul exact du prix par item sera fait dans le frontend/route
    const gangsterXp = DEAL_MISSION_MECHANICS.gangster_xp_per_deal;

    // Marquer les gangsters en transit
    for (const g of gangsters) {
      await gangMemberRepo().update(
        { gang_id: g.gang_id, player_id: g.player_id },
        { in_transit: true },
      );
    }

    return {
      success: true,
      revenue: 0, // Sera calculé par la route avec les prix réels des items
      price_multiplier: priceMultiplier,
      gangster_xp: gangsterXp,
    };
  }

  /**
   * Libérer automatiquement les prisonniers dont la peine est terminée
   * Appelé par CRON toutes les minutes
   */
  static async releaseExpiredPrisoners(): Promise<number> {
    // Find all prisoners whose sentence has expired
    const expired = await healthRepo()
      .createQueryBuilder('h')
      .select('h.player_id')
      .where('h.imprisoned_until IS NOT NULL')
      .andWhere('h.imprisoned_until <= NOW()')
      .getRawMany();

    if (expired.length === 0) return 0;

    const playerIds: string[] = expired.map((r: any) => r.h_player_id || r.player_id);

    // Clear imprisonment
    await healthRepo()
      .createQueryBuilder()
      .update()
      .set({ imprisoned_until: null })
      .where('imprisoned_until IS NOT NULL')
      .andWhere('imprisoned_until <= NOW()')
      .execute();

    // Update judicial status + send notification for each released player
    for (const pid of playerIds) {
      try {
        await JudicialService.onPrisonRelease(pid);
      } catch (err) {
        console.error(`[Prison] onPrisonRelease error for :`, (err as Error).message);
      }
    }

    // R6 (2026-05-02) — Lazy POI : decrement prison.current_population pour
    // chaque libéré, et DELETE le POI si la prison se vide complètement
    // (current_population devient 0). Le POI sera recréé à la prochaine
    // incarcération via assignPrison (cf prison-assignment.service.ts:90-108).
    try {
      const { Prison } = await import('../models/Prison');
      const { POI } = await import('../models/POI');
      const prisonRepo = AppDataSource.getRepository(Prison);
      const poiRepo = AppDataSource.getRepository(POI);

      // Récupérer prison_id pour chaque player libéré (avant que prison_id ne soit reset)
      const phRows = await healthRepo()
        .createQueryBuilder('h')
        .select(['h.player_id', 'h.prison_id'])
        .where('h.player_id IN (:...ids)', { ids: playerIds })
        .andWhere('h.prison_id IS NOT NULL')
        .getMany();

      // Group par prison pour batcher decrement + check vidage
      const decrementsByPrison = new Map<number, number>();
      for (const ph of phRows) {
        if (ph.prison_id == null) continue;
        decrementsByPrison.set(ph.prison_id, (decrementsByPrison.get(ph.prison_id) || 0) + 1);
      }

      for (const [prisonId, decrement] of decrementsByPrison.entries()) {
        await prisonRepo.decrement({ id: prisonId }, 'current_population', decrement);
        // Recharge la row pour vérifier si la prison est vide maintenant
        const refreshed = await prisonRepo.findOneBy({ id: prisonId });
        if (refreshed && refreshed.current_population <= 0 && refreshed.poi_id) {
          // Vide — supprime le POI lazy et reset prison.poi_id
          await poiRepo.delete(refreshed.poi_id);
          await prisonRepo.update({ id: prisonId }, { poi_id: null, current_population: 0 });
        } else if (refreshed && refreshed.current_population < 0) {
          // Garde-fou : pas de population négative
          await prisonRepo.update({ id: prisonId }, { current_population: 0 });
        }
      }

      // Reset prison_id côté player_health (sortis = plus assignés)
      await healthRepo().update(
        { player_id: In(playerIds), prison_id: Not(IsNull()) },
        { prison_id: null },
      );
    } catch (err) {
      console.error('[Prison] Lazy POI cleanup error:', (err as Error).message);
    }

    return playerIds.length;
  }

  // ══════════════════════════════════════════════════════════════
  // MARKETPLACE PRISON — Cantine & Auxiliaire
  // ══════════════════════════════════════════════════════════════

  /**
   * Retourne les canaux de marché accessibles au joueur en prison
   * selon son cursus et ses missions complétées.
   */
  static async getAvailableMarketChannels(playerId: string) {
    const status = await PrisonService.getPrisonStatus(playerId);
    if (!status.is_imprisoned) return [];

    return PRISON_MARKET_CHANNELS.filter(channel => {
      // Vérifier le cursus requis
      if (channel.requires_cursus && channel.requires_cursus !== status.cursus) {
        return false;
      }
      // Vérifier la mission requise
      if (channel.requires_mission && !status.completed_missions.includes(channel.requires_mission)) {
        return false;
      }
      return true;
    });
  }

  /**
   * Acheter un item au marché prison (Cantine ou Auxiliaire).
   * Crée un item dans l'inventaire du joueur.
   */
  static async buyFromPrisonMarket(
    playerId: string,
    channelId: string,
    itemSubtype: string,
    quantity: number,
  ): Promise<PlayerInventory> {
    if (quantity < 1) throw new Error('Quantité invalide');

    // Vérifier emprisonnement
    const status = await PrisonService.getPrisonStatus(playerId);
    if (!status.is_imprisoned) throw new Error('Vous n\'êtes pas en prison');

    // Vérifier accès au canal
    const channels = await PrisonService.getAvailableMarketChannels(playerId);
    const channel = channels.find(c => c.id === channelId);
    if (!channel) throw new Error('Canal non accessible');

    // Trouver l'item dans le catalogue du canal
    const itemDef = channel.items.find(i => i.item_subtype === itemSubtype);
    if (!itemDef) throw new Error('Article non disponible dans ce canal');

    // Vérifier la limite quotidienne
    // (Simplification : on vérifie le total acheté aujourd'hui)
    if (quantity > itemDef.daily_limit) {
      throw new Error(`Limite quotidienne: ${itemDef.daily_limit} unités max`);
    }

    const totalCost = itemDef.price * quantity;

    // Vérifier et déduire les fonds
    const balances = await balancesRepo().findOneBy({ player_id: playerId });
    if (!balances) throw new Error('Joueur introuvable');

    if (itemDef.currency === 'infinite_light') {
      if (balances.infinite_light < totalCost) throw new Error('Fonds insuffisants (∞ Light)');
      balances.infinite_light -= totalCost;
    } else {
      if (balances.infinite_shadow < totalCost) throw new Error('Fonds insuffisants (∞ Shadow)');
      balances.infinite_shadow -= totalCost;
    }
    await balancesRepo().save(balances);

    // Créer ou incrémenter l'item en inventaire
    const existing = await inventoryRepo().findOne({
      where: {
        player_id: playerId,
        item_type: itemDef.item_type as any,
        item_subtype: itemDef.item_subtype,
        storage_condition: 'on_person',
      },
    });

    if (existing) {
      existing.quantity += quantity;
      return inventoryRepo().save(existing);
    }

    return inventoryRepo().save(inventoryRepo().create({
      player_id: playerId,
      item_type: itemDef.item_type as any,
      item_subtype: itemDef.item_subtype,
      quantity,
      quality: itemDef.default_quality,
      storage_condition: 'on_person',
      weight_grams: itemDef.weight_grams * quantity,
    }));
  }

  /**
   * Vendre des cigarettes à un PNJ codétenu (revente en prison).
   * Basé sur les compétences du joueur pour le prix de vente.
   */
  static async sellCigarettesToNpc(
    playerId: string,
    quantity: number,
  ): Promise<{ revenue: number; price_per_paquet: number }> {
    if (quantity < 1) throw new Error('Quantité invalide');

    const status = await PrisonService.getPrisonStatus(playerId);
    if (!status.is_imprisoned) throw new Error('Vous n\'êtes pas en prison');

    // Vérifier l'inventaire (paquets en priorité)
    const paquets = await inventoryRepo().findOne({
      where: {
        player_id: playerId,
        item_subtype: 'cigarettes_paquet',
        storage_condition: 'on_person',
      },
    });

    if (!paquets || paquets.quantity < quantity) {
      throw new Error('Stock de paquets insuffisant');
    }

    // Calculer le prix de vente basé sur les compétences
    const relevant = PRISON_CIGARETTE_RESALE.relevant_skills;
    let skillSum = 0;
    for (const s of relevant) {
      skillSum += await getSkillLevel(playerId, s);
    }
    const avgSkill = relevant.length > 0 ? skillSum / relevant.length : 0;

    // Interpolation prix entre min et max selon compétence
    const { mission_min_price_paquet, mission_max_price_paquet } = PRISON_CIGARETTE_RESALE;
    const skillFactor = Math.min(avgSkill / 100, 1);
    const pricePerPaquet = Math.round(
      mission_min_price_paquet + (mission_max_price_paquet - mission_min_price_paquet) * skillFactor
    );

    const revenue = pricePerPaquet * quantity;

    // Déduire les paquets
    paquets.quantity -= quantity;
    if (paquets.quantity <= 0) {
      await inventoryRepo().remove(paquets);
    } else {
      await inventoryRepo().save(paquets);
    }

    // Créditer en infinite_shadow (revente illégale)
    await balancesRepo().increment({ player_id: playerId }, 'infinite_shadow', revenue);

    return { revenue, price_per_paquet: pricePerPaquet };
  }

  // ══════════════════════════════════════════════════════════════
  // CARTE PRISON — Layout, interactions, position
  // ══════════════════════════════════════════════════════════════

  /**
   * Retourne le plan complet de la prison accessible au joueur.
   */
  static async getPrisonMap(playerId: string) {
    const status = await PrisonService.getPrisonStatus(playerId);
    if (!status.is_imprisoned) return { floors: [], locations: [] };

    // Filtrer les lieux selon le cursus
    const accessibleLocations = PRISON_LAYOUT.filter(loc => {
      if (loc.requires_cursus && loc.requires_cursus !== status.cursus) return false;
      if (loc.requires_mission && !status.completed_missions.includes(loc.requires_mission)) return false;
      return true;
    });

    return {
      floors: PRISON_FLOORS,
      locations: accessibleLocations,
    };
  }

  /**
   * Exécuter une interaction dans un lieu de la prison.
   */
  static async executeInteraction(
    playerId: string,
    locationId: string,
    interaction: PrisonInteraction,
  ): Promise<{
    success: boolean;
    message: string;
    effects?: Record<string, number>;
    item_produced?: { item_type: string; item_subtype: string; quantity: number };
  }> {
    const status = await PrisonService.getPrisonStatus(playerId);
    if (!status.is_imprisoned) throw new Error('Vous n\'êtes pas en prison');

    const location = getLocationById(locationId);
    if (!location) throw new Error('Lieu introuvable');

    // Vérifier que l'interaction est possible dans ce lieu
    if (!location.interactions.includes(interaction)) {
      throw new Error(`Interaction "${interaction}" non disponible ici`);
    }

    // Vérifier accès au lieu
    if (location.requires_cursus && location.requires_cursus !== status.cursus) {
      throw new Error('Accès réservé à un autre cursus');
    }

    // Interactions avec effets définis
    const effectDef = (PRISON_INTERACTION_EFFECTS as any)[interaction];
    if (effectDef) {
      // Appliquer les effets sur les jauges
      if (effectDef.gauge_effects) {
        const updates: Record<string, () => string> = {};
        for (const [gauge, delta] of Object.entries(effectDef.gauge_effects)) {
          updates[gauge] = () => `GREATEST(0, LEAST(100, ${gauge} + ${delta}))`;
        }
        if (Object.keys(updates).length > 0) {
          await gaugesRepo()
            .createQueryBuilder()
            .update()
            .set(updates)
            .where('player_id = :pid', { pid: playerId })
            .execute();
        }
      }

      // Appliquer XP compétences (skills stockés par skill_id + level)
      if (effectDef.skill_xp) {
        for (const [skillName, xpGain] of Object.entries(effectDef.skill_xp)) {
          const sid = skillNameToId(skillName);
          if (!sid || !xpGain) continue;

          let skill = await skillsRepo().findOne({
            where: { player_id: playerId, skill_id: sid },
          });

          if (!skill) {
            // Créer l'entrée skill si elle n'existe pas
            skill = skillsRepo().create({
              player_id: playerId,
              skill_id: sid,
              level: 0,
              experience: 0,
            });
          }

          skill.experience += xpGain as number;
          // Level up si assez d'XP (100 * level requis)
          const nextLevelXp = 100 * (skill.level + 1);
          if (skill.experience >= nextLevelXp && skill.level < 100) {
            skill.level += 1;
            skill.experience -= nextLevelXp;
          }
          await skillsRepo().save(skill);
        }
      }

      // Produire un item si applicable
      let itemProduced: { item_type: string; item_subtype: string; quantity: number } | undefined;
      if (effectDef.produces_item) {
        const pi = effectDef.produces_item;
        const existing = await inventoryRepo().findOne({
          where: {
            player_id: playerId,
            item_type: pi.item_type,
            item_subtype: pi.item_subtype,
            storage_condition: 'on_person',
          },
        });
        if (existing) {
          existing.quantity += pi.quantity;
          await inventoryRepo().save(existing);
        } else {
          await inventoryRepo().save(inventoryRepo().create({
            player_id: playerId,
            item_type: pi.item_type,
            item_subtype: pi.item_subtype,
            quantity: pi.quantity,
            quality: 2,
            storage_condition: 'on_person',
            weight_grams: 200 * pi.quantity,
          }));
        }
        itemProduced = pi;
      }

      // Consommer un item si applicable
      if (effectDef.consumes_item) {
        const ci = effectDef.consumes_item;
        const inv = await inventoryRepo().findOne({
          where: {
            player_id: playerId,
            item_type: ci.item_type,
            item_subtype: ci.item_subtype,
            storage_condition: 'on_person',
          },
        });
        if (inv && inv.quantity >= ci.quantity) {
          inv.quantity -= ci.quantity;
          if (inv.quantity <= 0) {
            await inventoryRepo().remove(inv);
          } else {
            await inventoryRepo().save(inv);
          }
        }
      }

      return {
        success: true,
        message: `Interaction "${interaction}" effectuée dans ${location.name}.`,
        effects: effectDef.gauge_effects,
        item_produced: itemProduced,
      };
    }

    // Pour les interactions sans effets prédéfinis (discuter, etc.)
    return {
      success: true,
      message: `Interaction "${interaction}" effectuée dans ${location.name}.`,
    };
  }

  /**
   * Calculer le bonus combat d'un joueur en prison
   * basé sur les armes blanches en sa possession.
   */
  static async getPrisonCombatBonus(playerId: string): Promise<number> {
    const weapons = await inventoryRepo().find({
      where: {
        player_id: playerId,
        item_type: 'weapon' as any,
        storage_condition: 'on_person',
      },
    });

    let bonus = 0;
    for (const w of weapons) {
      const weaponBonus = PRISON_WEAPON_COMBAT_BONUS[w.item_subtype];
      if (weaponBonus) bonus += weaponBonus;
    }
    return bonus;
  }

  /**
   * Simuler une fouille aléatoire.
   * Appelé par CRON ou à certaines interactions.
   */
  static async performRandomSearch(playerId: string): Promise<{
    searched: boolean;
    contraband_found: boolean;
    confiscated_items: string[];
    mitard: boolean;
  }> {
    const status = await PrisonService.getPrisonStatus(playerId);
    if (!status.is_imprisoned) return { searched: false, contraband_found: false, confiscated_items: [], mitard: false };

    // Probabilité de fouille (réduite par discrétion)
    const discretion = await getSkillLevel(playerId, 'Discrétion');
    const searchChance = Math.max(1,
      PRISON_SEARCH_MECHANICS.hourly_search_probability -
      discretion * PRISON_SEARCH_MECHANICS.discretion_reduction_per_point
    );

    const roll = Math.random() * 100;
    if (roll > searchChance) {
      return { searched: false, contraband_found: false, confiscated_items: [], mitard: false };
    }

    // Fouille ! Chercher les items de contrebande
    const allItems = await inventoryRepo().find({
      where: { player_id: playerId, storage_condition: 'on_person' },
    });

    const contrabandItems = allItems.filter(
      item => (PRISON_SEARCH_MECHANICS.contraband_subtypes as readonly string[]).includes(item.item_subtype)
    );

    if (contrabandItems.length === 0) {
      return { searched: true, contraband_found: false, confiscated_items: [], mitard: false };
    }

    // Confiscation
    const confiscatedNames: string[] = [];
    for (const item of contrabandItems) {
      confiscatedNames.push(`${item.item_subtype} x${item.quantity}`);
      await inventoryRepo().remove(item);
    }

    // Mitard
    const health = await healthRepo().findOneBy({ player_id: playerId });
    if (health?.imprisoned_until) {
      const mitardMs = PRISON_SEARCH_MECHANICS.mitard_duration_hours * 60 * 60 * 1000;
      health.imprisoned_until = new Date(health.imprisoned_until.getTime() + mitardMs);
      await healthRepo().save(health);
    }

    return {
      searched: true,
      contraband_found: true,
      confiscated_items: confiscatedNames,
      mitard: true,
    };
  }

  // ══════════════════════════════════════════════════════════════
  // TÉLÉPHONE PRISON
  // ══════════════════════════════════════════════════════════════

  /**
   * Retourne le statut téléphonique du joueur en prison.
   * - Téléphone normal confisqué
   * - MiniKom P1 disponible si acheté
   * - SIM clandestine réduit la traçabilité
   */
  static async getPrisonPhoneStatus(playerId: string) {
    const status = await PrisonService.getPrisonStatus(playerId);
    if (!status.is_imprisoned) return null;

    // Le joueur possède-t-il un MiniKom P1 ?
    const miniKom = await inventoryRepo().findOne({
      where: {
        player_id: playerId,
        item_subtype: 'minikom_p1',
        storage_condition: 'on_person',
      },
    });

    // SIM clandestine ?
    const clandestineSim = await inventoryRepo().findOne({
      where: {
        player_id: playerId,
        item_subtype: 'sim_clandestine',
        storage_condition: 'on_person',
      },
    });

    // Contacts limités au MiniKom (max 5)
    const player = await playerRepo().findOneBy({ id: playerId });
    const allContacts = player?.contacts ?? [];
    const miniKomContacts = allContacts.slice(0, PRISON_PHONE_RULES.max_contacts_minikom);

    // Phase 8.7 (2026-04-29) — "Gérer Extérieur" : on autorise le joueur
    // emprisonné à donner des ordres à son gang via son bras droit SI :
    //   1. il a un MiniKom on_person
    //   2. il y a un bras_droit actif (non hospitalisé)
    // Le bras_droit info vient de PrisonStatus.bras_droit_active déjà calculé.
    let brasDroit: { player_id: string; name: string | null } | null = null;
    if (status.bras_droit_active) {
      const gm = await gangMemberRepo().findOne({ where: { player_id: playerId } });
      if (gm) {
        const bd = await gangMemberRepo().findOne({
          where: { gang_id: gm.gang_id, role: 'bras_droit' as any },
          relations: ['player'],
        });
        if (bd) {
          brasDroit = {
            player_id: bd.player_id,
            name: (bd as any).player?.character_name ?? null,
          };
        }
      }
    }

    const canDispatchOrders = !!miniKom && !!brasDroit && status.bras_droit_active;

    return {
      normal_phone_confiscated: PRISON_PHONE_RULES.normal_phone_confiscated,
      has_prison_phone: !!miniKom,
      phone_model: miniKom ? PRISON_PHONE_RULES.prison_phone_model : null,
      has_clandestine_sim: !!clandestineSim,
      traceability: clandestineSim
        ? PRISON_PHONE_RULES.traceability_with_clandestine_sim
        : (miniKom ? 90 : null),
      available_contacts: miniKom ? miniKomContacts : [],
      parloir_cost: PRISON_PHONE_RULES.parloir_call_cost,
      can_use_parloir: status.access.phone_parloir,
      can_use_smuggled: 'smuggled_phone' in status.access && !!(status.access as any).smuggled_phone,
      // Phase 8.7 — Gérer Extérieur
      bras_droit_active: status.bras_droit_active,
      bras_droit: brasDroit,
      can_dispatch_orders: canDispatchOrders,
    };
  }
}
