/**
 * Phase 17 Phase 3 (2026-05-04) — Mission "Recruter" wizard multi-POI.
 *
 * Consigne user verbatim 2026-05-04 :
 *   "Cibler Poi parmi (filtre auto lors de la sélection de cet ordre)
 *    bars, nightclubs, casino, warehouse, dealpoint, docks, ports de
 *    plaisance, commissariat, prison. On peut cliquer un ou plusieurs
 *    (jusqu'à 5 pois, [...] + 20 minute sur chaque lieu).
 *    Candidats : 1 à 3 si un seul lieu, sinon 0 à 3 par lieu (avec
 *    toujours un minimum 1, si on par recruter, on revient au moins
 *    avec une recrue).
 *    risque baggarre 5% (notif si ca arrive [...] PV perdus 10 à 50).
 *    Si Baggarre risque police : 30% avec uniquement amande pour
 *    Grabuge 500 infinite lumiere (si ne les possèdes pas, alors
 *    amnéstié, mais chaleur +3)
 *    Cout ressource : augmentation de chaleur de 1pt par lieu visité
 *    et essences si véhicule / véhicules assigné/s."
 *
 * Itération 1 (Phase 3a) : exécution SYNCHRONE — pas de journey en
 * transit pour les gangsters, le résultat est calculé immédiatement
 * et les candidats ajoutés au pool. Le frontend pourra afficher un
 * timer cosmétique pour la durée totale calculée. Une itération
 * future (Phase 7) pourra basculer en ScheduledOrder asynchrone
 * (vrai travel time, gangsters in_transit pendant la mission).
 */

import { AppDataSource } from '../config/database';
import { In } from 'typeorm';
import { GangMember } from '../models/GangMember';
import { Player } from '../models/Player';
import { PlayerHealth } from '../models/PlayerHealth';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerGauges } from '../models/PlayerGauges';
import { Notification } from '../models/Notification';
import { NpcRecruitService } from './npc-recruit.service';
import { CartelNpcRecruitService } from './cartel-npc-recruit.service';
import { TransactionService } from './transaction.service';

const gmRepo = () => AppDataSource.getRepository(GangMember);
const playerRepo = () => AppDataSource.getRepository(Player);
const phRepo = () => AppDataSource.getRepository(PlayerHealth);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const gaugesRepo = () => AppDataSource.getRepository(PlayerGauges);
const notifRepo = () => AppDataSource.getRepository(Notification);

/**
 * Phase 17 Phase 3 fix (2026-05-04) — POI types acceptés par la mission Recruter.
 *
 * Le frontend reçoit `target.type` ∈ {business, infrastructure, warehouse,
 * point_de_deal, residence, hideout, …} via getPoiDetails. Pour les
 * bars/nightclubs/casinos, le poi_type est `'business'` avec `business_type`
 * dans le sous-objet linked. Pour les commissariats/prisons/hôpitaux,
 * c'est `'infrastructure'` avec un `infra_type`.
 *
 * On accepte donc 4 types POI génériques + on valide finement le sous-type
 * via `BUSINESS_TYPE_WHITELIST` et `INFRA_TYPE_WHITELIST` côté backend
 * (defense in depth).
 */
export const RECRUIT_ELIGIBLE_POI_TYPES = [
  'business',        // bar, nightclub, casino, port_ferry, restaurant
  'warehouse',       // tout warehouse player ou NPC
  'point_de_deal',   // posé par joueur ou NPC
  'infrastructure',  // courthouse, police_station, prison, port (filtré ci-dessous)
] as const;

export type RecruitEligiblePoiType = typeof RECRUIT_ELIGIBLE_POI_TYPES[number];

/** Sous-types business autorisés pour Recruter (ambiance underground). */
const BUSINESS_TYPE_WHITELIST = new Set([
  'bar', 'nightclub', 'casino', 'port_ferry', 'restaurant',
]);

/** Sous-types infrastructure autorisés. */
const INFRA_TYPE_WHITELIST = new Set([
  'police_station', 'prison',
  // Note : 'courthouse', 'hospital' ont leur propre action recruter
  // spécialiste (avocat / médecin perso) — pas pertinent pour la mission
  // Recruter générique de gangsters NPC.
]);

/** Coût mission Recruter (configurable via GameSettings ultérieurement). */
const PER_POI_MINUTES = 20;            // 20 min sur place par POI
const PER_POI_HEAT = 1;                // +1 chaleur par lieu
const FIGHT_RISK_PCT = 5;              // 5% bagarre/lieu
const FIGHT_PV_LOSS_MIN = 10;
const FIGHT_PV_LOSS_MAX = 50;
const POLICE_RISK_AFTER_FIGHT_PCT = 30; // 30% police si bagarre
const POLICE_FINE_AMOUNT = 500;        // ∞ lumière "Grabuge"
const AMNESTY_HEAT_PENALTY = 3;        // +3 chaleur si pas de fonds pour l'amende

export interface RecruitMissionInput {
  scope: { type: 'gang' | 'cartel'; id: string };
  team: string[];                      // player_ids (NPCs gangsters + soi-même)
  include_player: boolean;
  target_pois: Array<{
    poi_type: RecruitEligiblePoiType;
    poi_id: string;
    label?: string;                    // pour le résumé notif
  }>;
  vehicle_ids?: string[];              // pour calcul essence (Phase 3a : non appliqué encore)
}

export interface RecruitMissionResult {
  success: boolean;
  message: string;
  visited_pois: number;
  total_minutes: number;
  candidates_generated: number;
  pv_losses: Array<{ player_id: string; pv_lost: number }>;
  fights: Array<{ poi_index: number; police_amende: number; chaleur_amnesty: number }>;
  total_chaleur_added: number;
  per_poi_summary: Array<{
    poi_index: number;
    poi_type: string;
    poi_id: string;
    candidates: number;
    fight: boolean;
  }>;
}

export class RecruitMissionService {

  /**
   * Lance la mission Recruter et calcule immédiatement le résultat.
   * Append les candidats au pool de l'owner (NpcRecruitPool ou
   * CartelRecruitPool selon scope).
   */
  static async runMission(
    playerId: string,
    input: RecruitMissionInput,
  ): Promise<RecruitMissionResult> {
    // ─── Validation ───
    if (!Array.isArray(input.target_pois) || input.target_pois.length === 0) {
      throw new Error('Sélectionne au moins 1 POI à visiter pour recruter.');
    }
    if (input.target_pois.length > 5) {
      throw new Error('Maximum 5 POIs par mission Recruter.');
    }
    // Validation type POI + sous-type (defense in depth — frontend filtre
    // déjà côté UI). Phase 17 fix 2026-05-04 : poi.type est générique
    // (business / infrastructure / warehouse / point_de_deal), on
    // valide finement le sous-type via lookup DB.
    const { Business } = await import('../models/Business');
    const { POI } = await import('../models/POI');
    const businessRepo = AppDataSource.getRepository(Business);
    const poiRepo = AppDataSource.getRepository(POI);

    for (const t of input.target_pois) {
      if (!(RECRUIT_ELIGIBLE_POI_TYPES as readonly string[]).includes(t.poi_type)) {
        throw new Error(`Type POI "${t.poi_type}" non éligible. Choisis bar/nightclub/casino, entrepôt, point de deal, commissariat ou prison.`);
      }
      // Validation fine sous-type
      if (t.poi_type === 'business') {
        const biz = await businessRepo.findOne({ where: { id: t.poi_id } });
        if (!biz) {
          throw new Error(`Commerce introuvable (id=${t.poi_id}).`);
        }
        if (!BUSINESS_TYPE_WHITELIST.has(biz.type)) {
          throw new Error(`Le commerce "${biz.type}" n'est pas un lieu de recrutement (utilise bar, nightclub, casino, port_ferry ou restaurant).`);
        }
      } else if (t.poi_type === 'infrastructure') {
        // poi_id ici est le POI.id direct (pas une entity_id)
        const poi = await poiRepo.findOne({ where: { id: t.poi_id } });
        if (!poi) {
          throw new Error(`POI infrastructure introuvable (id=${t.poi_id}).`);
        }
        // Resolve infra_type via mapping icon -> infra_type
        const { MapActionService } = await import('./map-action.service');
        const infraType = await (MapActionService as any).resolveInfraType?.('infrastructure', t.poi_id);
        if (!infraType || !INFRA_TYPE_WHITELIST.has(infraType)) {
          throw new Error(`Cette infrastructure n'est pas un lieu de recrutement (utilise commissariat ou prison).`);
        }
      }
      // warehouse + point_de_deal : pas de filtrage sub-type (tout est éligible)
    }

    if (!Array.isArray(input.team) || input.team.length === 0) {
      throw new Error('Au moins un gangster (ou soi-même) doit partir recruter.');
    }
    const teamIds = [...input.team];
    if (input.include_player && !teamIds.includes(playerId)) teamIds.push(playerId);
    if (teamIds.length > 5) {
      throw new Error('Équipe max 5 (incluant le joueur).');
    }

    // Vérifie scope ownership minimal (gang membership ou cartel membership)
    if (input.scope.type === 'gang') {
      const gm = await gmRepo().findOne({ where: { player_id: playerId, gang_id: input.scope.id } });
      if (!gm) throw new Error("Vous n'êtes pas dans ce gang.");
    } else {
      const { CartelMember } = await import('../models/CartelMember');
      const gmSelf = await gmRepo().findOne({ where: { player_id: playerId } });
      if (!gmSelf) throw new Error('Pas de gang.');
      const cm = await AppDataSource.getRepository(CartelMember).findOne({
        where: { gang_id: gmSelf.gang_id, cartel_id: input.scope.id, status: 'active' as any },
      });
      if (!cm) throw new Error("Vous n'êtes pas dans ce cartel.");
    }

    // ─── Calcul mission ───
    const isSinglePoi = input.target_pois.length === 1;
    const totalMinutes = input.target_pois.length * PER_POI_MINUTES;
    let totalChaleurAdded = 0;
    let candidatesTotal = 0;
    const fights: RecruitMissionResult['fights'] = [];
    const pvLosses: RecruitMissionResult['pv_losses'] = [];
    const perPoi: RecruitMissionResult['per_poi_summary'] = [];

    for (let i = 0; i < input.target_pois.length; i++) {
      const poi = input.target_pois[i];
      let candidatesAtPoi: number;
      if (isSinglePoi) {
        // 1 lieu → 1-3 candidats (jamais 0)
        candidatesAtPoi = 1 + Math.floor(Math.random() * 3); // 1, 2 ou 3
      } else {
        // multi-POI → 0-3 par lieu, on garantira ≥ 1 total après la boucle
        candidatesAtPoi = Math.floor(Math.random() * 4); // 0, 1, 2 ou 3
      }
      candidatesTotal += candidatesAtPoi;

      // Bagarre 5%
      let fight = false;
      if (Math.random() * 100 < FIGHT_RISK_PCT) {
        fight = true;
        // PV loss 10-50 par membre de l'équipe (ceux qui sont des players)
        for (const pid of teamIds) {
          const pvLost = FIGHT_PV_LOSS_MIN + Math.floor(Math.random() * (FIGHT_PV_LOSS_MAX - FIGHT_PV_LOSS_MIN + 1));
          await RecruitMissionService.applyPvLoss(pid, pvLost);
          pvLosses.push({ player_id: pid, pv_lost: pvLost });
        }

        // Police 30% si bagarre
        let policeAmende = 0;
        let chaleurAmnesty = 0;
        if (Math.random() * 100 < POLICE_RISK_AFTER_FIGHT_PCT) {
          // Tente l'amende 500 ∞ light
          const balances = await balancesRepo().findOneBy({ player_id: playerId });
          const lightAvail = Number(balances?.infinite_light) || 0;
          if (lightAvail >= POLICE_FINE_AMOUNT) {
            await balancesRepo().createQueryBuilder().update()
              .set({ infinite_light: () => `GREATEST(0, infinite_light - ${POLICE_FINE_AMOUNT})` })
              .where('player_id = :id', { id: playerId })
              .execute();
            await TransactionService.log({
              player_id: playerId,
              category: 'gang',
              type: 'out',
              amount: POLICE_FINE_AMOUNT,
              currency: 'infinite_light',
              description: `Amende police (Grabuge) — mission Recruter POI ${poi.poi_type}`,
            });
            policeAmende = POLICE_FINE_AMOUNT;
          } else {
            // Pas de fonds → amnistié + chaleur +3
            await RecruitMissionService.addHeat(playerId, AMNESTY_HEAT_PENALTY);
            totalChaleurAdded += AMNESTY_HEAT_PENALTY;
            chaleurAmnesty = AMNESTY_HEAT_PENALTY;
          }
        }
        fights.push({ poi_index: i, police_amende: policeAmende, chaleur_amnesty: chaleurAmnesty });
      }

      // +1 chaleur par lieu (toujours, même sans bagarre)
      await RecruitMissionService.addHeat(playerId, PER_POI_HEAT);
      totalChaleurAdded += PER_POI_HEAT;

      perPoi.push({
        poi_index: i,
        poi_type: poi.poi_type,
        poi_id: poi.poi_id,
        candidates: candidatesAtPoi,
        fight,
      });
    }

    // Garantie min 1 candidat total si multi-POI (consigne user)
    if (!isSinglePoi && candidatesTotal === 0) {
      // Force +1 sur le dernier POI
      candidatesTotal = 1;
      perPoi[perPoi.length - 1].candidates = 1;
    }

    // ─── Append candidats au pool ───
    if (candidatesTotal > 0) {
      if (input.scope.type === 'gang') {
        await NpcRecruitService.refreshPoolForPlayer(playerId, false, {
          append: true,
          forcedSize: candidatesTotal,
        });
      } else {
        await CartelNpcRecruitService.refreshPoolForCartel(input.scope.id, false, {
          append: true,
          forcedSize: candidatesTotal,
        });
      }
    }

    // ─── Notif owner avec résumé ───
    const fightCount = fights.length;
    const summary =
      `Mission Recruter terminée. ${input.target_pois.length} lieu(x) visité(s) en ${totalMinutes} min. ` +
      `${candidatesTotal} candidat(s) ajouté(s) au pool. ` +
      (fightCount > 0
        ? `${fightCount} bagarre(s) — ${pvLosses.length} blessure(s) gérée(s). `
        : 'Aucune bagarre. ') +
      `Chaleur +${totalChaleurAdded}.`;

    try {
      await notifRepo().save(notifRepo().create({
        player_id: playerId,
        type: 'system',
        title: 'Recrutement terrain',
        message: summary,
      }));
    } catch { /* silent */ }

    return {
      success: true,
      message: summary,
      visited_pois: input.target_pois.length,
      total_minutes: totalMinutes,
      candidates_generated: candidatesTotal,
      pv_losses: pvLosses,
      fights,
      total_chaleur_added: totalChaleurAdded,
      per_poi_summary: perPoi,
    };
  }

  // ─── Helpers ────────────────────────────────────────────────

  private static async applyPvLoss(playerId: string, pvLost: number): Promise<void> {
    if (pvLost <= 0) return;
    const ph = await phRepo().findOneBy({ player_id: playerId });
    if (!ph) return;
    const current = Number(ph.physical_health ?? 0);
    const newPv = Math.max(0, current - pvLost);
    await phRepo().update({ player_id: playerId }, { physical_health: newPv });
  }

  private static async addHeat(playerId: string, delta: number): Promise<void> {
    if (delta <= 0) return;
    await gaugesRepo()
      .createQueryBuilder()
      .update()
      .set({ chaleur: () => `LEAST(100, GREATEST(0, chaleur + ${delta}))` })
      .where('player_id = :pid', { pid: playerId })
      .execute();
  }
}
