/**
 * Phase 8.5d (2026-04-29) — Service centralisé hôpital.
 *
 * Spec user :
 *   - GPS auto à l'hôpital le plus proche lors de l'hospitalisation
 *   - Frais 3000 ∞ Light à la sortie (clamp si insuffisant, pas de dette)
 *   - Sortie via cron 60s : reset PV à 100 + débit frais + reset hospital_lat/lon
 *   - Si player a `owned_hospital_business_id` ET hospitalisé là → évasion auto
 *   - Lightbox flavor "Ça a chauffé grave..." si hospitalisation cause GIGN
 *
 * Le service expose un `hospitalize` global qui doit être utilisé partout
 * (vs setter direct `hospitalized_until` qui bypass GPS auto + flavor).
 */
import { AppDataSource } from '../config/database';
import { LessThanOrEqual, MoreThan } from 'typeorm';
import { PlayerHealth } from '../models/PlayerHealth';
import { Player } from '../models/Player';
import { Business } from '../models/Business';
import { Notification } from '../models/Notification';
import { GameSettingsService } from './game-settings.service';
import { NearestPoiService } from './nearest-poi.service';
import { PaymentService } from './payment.service';
import { HealthService } from './health.service';

const phRepo = () => AppDataSource.getRepository(PlayerHealth);
const playerRepo = () => AppDataSource.getRepository(Player);
const businessRepo = () => AppDataSource.getRepository(Business);
const notifRepo = () => AppDataSource.getRepository(Notification);

/**
 * Phase 8 v2 (2026-05-01) — élargi pour matcher Q8 spec user :
 *   - 'gign'      : attaque GIGN (raid territoire). Drive held +8j à la
 *                   sortie naturelle, ou redirect tribunal/prison si held>0
 *                   ou pending judicial.
 *   - 'police'    : interpellation police classique. Drive
 *                   JudicialFlowService.enterGardeAVue (scene police) à
 *                   la sortie.
 *   - 'combat'    : combat joueur ou gang. Sortie normale (sauf si held>0
 *                   ou pending judicial → redirect).
 *   - 'overdose'  : surdose drogue. Sortie normale.
 *   - 'other'     : fallback.
 *
 * 'gign_combat' est conservé en alias rétro-compat (= 'gign').
 */
export type HospitalizeReason = 'combat' | 'gign' | 'gign_combat' | 'police' | 'overdose' | 'other';

export interface HospitalizeResult {
  hospitalized: boolean;
  /** True si évasion auto (player owned_hospital matchait l'hôpital où il aurait dû aller). */
  auto_escaped: boolean;
  /** UUID du business hospital où le joueur a été envoyé (null si auto_escaped). */
  hospital_business_id: string | null;
  hospitalized_until: Date | null;
}

export class HospitalService {

  /**
   * Hospitalise un joueur. Trigger global :
   *   1. Si player.owned_hospital_business_id ET c'est cet hôpital qui est le
   *      plus proche → évasion auto (skip hospitalize, PV reset à 100, flavor notif).
   *   2. Sinon : set hospitalized_until=now+24h, set Player.hospital_lat/lon +
   *      current_lat/lon = nearest hospital, physical_health=5.
   *   3. Notif système (avec flavor GIGN si reason='gign_combat').
   */
  static async hospitalize(playerId: string, reason: HospitalizeReason = 'other', _legacyDurationHours?: number): Promise<HospitalizeResult> {
    const player = await playerRepo().findOneBy({ id: playerId });
    if (!player) {
      return { hospitalized: false, auto_escaped: false, hospital_business_id: null, hospitalized_until: null };
    }

    // Normalize legacy alias 'gign_combat' → 'gign' (spec Q8)
    const normalizedReason: HospitalizeReason = reason === 'gign_combat' ? 'gign' : reason;

    const fromLat = Number(player.current_lat) || Number(player.start_lat) || 48.8566;
    const fromLon = Number(player.current_lon) || Number(player.start_lon) || 2.3522;

    const nearest = await NearestPoiService.findNearestHospital(fromLat, fromLon);
    if (!nearest) {
      console.error('[Hospital] No nearest hospital found, fallback no-op');
      return { hospitalized: false, auto_escaped: false, hospital_business_id: null, hospitalized_until: null };
    }

    // Phase 8 v2 (2026-05-01) — Hôpital possédé par le joueur :
    // PLUS d'évasion auto à 100 PV. Le joueur entre normalement à 1 PV
    // mais bénéficie d'un soin x2 plus rapide (5h total au lieu de 10h)
    // via hospital_owned_rate=true → ticks +9 first puis +10/30min.
    const isOwned = !!player.owned_hospital_business_id
      && player.owned_hospital_business_id === nearest.id;

    // Spec user verbatim :
    //   "1 pts entrée à hôpital. À la fin de la première demi-heure +4
    //    (=5). Puis +5 par demi-heure. Sortie à 100 = 10h total.
    //    Si on possède : +1 entrée + 9 first → 10, puis +10/30min. 5h total."
    // Calcul : 1 + 4 + 5×19 = 100 → 19 ticks suivants après le premier
    //   = 0.5h (premier) + 19×0.5h = 10h.
    // Owned : 1 + 9 + 10×9 = 100 → 9 ticks suivants → 0.5h + 4.5h = 5h.
    const totalHours = isOwned ? 5 : 10;
    const until = new Date(Date.now() + totalHours * 3600 * 1000);

    await phRepo().update(
      { player_id: playerId },
      {
        hospitalized_until: until,
        physical_health: 1,
        healing_pts_remaining: 99,
        healing_next_tick_at: new Date(Date.now() + 30 * 60 * 1000),
        hospital_reason: normalizedReason,
        hospital_owned_rate: isOwned,
      },
    );
    await playerRepo().update(
      { id: playerId },
      {
        current_lat: nearest.lat,
        current_lon: nearest.lon,
        hospital_lat: nearest.lat,
        hospital_lon: nearest.lon,
        in_transit: false,
        active_vehicle_id: null,
      },
    );

    // Notification flavor selon raison
    let flavorTitle: string;
    let flavorMsg: string;
    if (normalizedReason === 'gign') {
      flavorTitle = 'Réveil sous perfusion';
      flavorMsg = `Ça a chauffé grave, le GIGN a débarqué et vous a flanqué une raclée. Le territoire est à mal, et vous allez pas sortir tout de suite. ${totalHours}h d'hospitalisation à ${nearest.name}.`;
    } else if (normalizedReason === 'police') {
      flavorTitle = 'Interpellation';
      flavorMsg = `La police vous a maîtrisé. Direction l'hosto, on vous remet d'aplomb avant la suite des événements. ${totalHours}h à ${nearest.name}.`;
    } else if (isOwned) {
      flavorTitle = 'Soin VIP — votre hôpital';
      flavorMsg = `Vous êtes hospitalisé dans votre propre hôpital. Le personnel s'occupe de vous en priorité. Soin accéléré : ${totalHours}h.`;
    } else {
      flavorTitle = 'À l\'hôpital';
      flavorMsg = `Tes blessures sont sérieuses. ${totalHours}h d'hospitalisation à ${nearest.name}.`;
    }
    try {
      await notifRepo().save(notifRepo().create({
        player_id: playerId,
        type: 'system',
        title: flavorTitle,
        message: flavorMsg,
      }));
    } catch { /* silent */ }

    return {
      hospitalized: true,
      auto_escaped: false,
      hospital_business_id: nearest.id,
      hospitalized_until: until,
    };
  }

  /**
   * CRON 60s : libère les joueurs dont `hospitalized_until <= now` OU
   * `physical_health >= 100` (cas où le soin progressif a atteint 100
   * avant la durée totale).
   *
   * Phase 8 v2 (2026-05-01) — comportement post-release selon hospital_reason :
   *   - 'gign' :
   *       - if held_remaining_ms > 0 OR pending judicial → redirect tribunal/prison
   *       - else → sortie + held_remaining_ms += 8 jours
   *   - 'police' :
   *       - trigger JudicialFlowService.enterGardeAVue (scene police)
   *   - 'combat' :
   *       - if held_remaining_ms > 0 OR pending judicial → redirect
   *       - else → sortie normale
   *   - 'overdose' / 'other' / null :
   *       - sortie normale, pas de held ajouté
   *
   * Tous les cas : frais 3000 ∞ Light (clamp si insuffisant, pas de dette),
   * reset hospital_lat/lon, healing reset (via healToFull).
   *
   * Idempotent : ne touche que les joueurs avec hospitalized_until passé
   * OU physical_health == 100 (soin progressif atteint le cap avant l'heure).
   */
  static async processReleases(): Promise<{ released: number; total_fees: number }> {
    const now = new Date();
    // Sortie si hospitalized_until atteint OU PV atteint 100 avant l'heure
    const expired = await phRepo()
      .createQueryBuilder('ph')
      .where('ph.hospitalized_until IS NOT NULL')
      .andWhere('(ph.hospitalized_until <= :now OR ph.physical_health >= 100)', { now })
      .getMany();

    let released = 0;
    let totalFees = 0;
    const fee = await GameSettingsService.get<number>('hospital.exit_fee_default', 3000);
    const heldGignDays = await GameSettingsService.get<number>('hospital.gign_held_days', 8);

    for (const ph of expired) {
      try {
        // Carte santé → gratuit
        const hasCard = await HealthService.hasCareCard(ph.player_id);
        let actualFee = 0;

        if (!hasCard && fee > 0) {
          const { PlayerBalances } = await import('../models/PlayerBalances');
          const balRepo = AppDataSource.getRepository(PlayerBalances);
          const bal = await balRepo.findOneBy({ player_id: ph.player_id });
          const totalAvail = (Number(bal?.infinite_shadow) || 0) + (Number(bal?.infinite_light) || 0);
          actualFee = Math.min(fee, totalAvail);
          if (actualFee > 0) {
            await PaymentService.debitMix({
              ownerType: 'player',
              ownerId: ph.player_id,
              amount: actualFee,
              category: 'health',
              description: 'Frais hôpital (clamp si insuffisant)',
            });
          }
        }

        // Capture le contexte avant le reset
        const reason = ph.hospital_reason;
        const heldRemainingMs = Number(ph.held_remaining_ms || 0);
        const hasPendingJudicial = heldRemainingMs > 0;

        // Reset PV à 100 + déhospitalize + clear healing + clear hospital_reason/owned_rate
        await HealthService.healToFull(ph.player_id);
        await phRepo().update(
          { player_id: ph.player_id },
          { hospital_reason: null, hospital_owned_rate: false },
        );
        await playerRepo().update(
          { id: ph.player_id },
          { hospital_lat: null, hospital_lon: null },
        );

        // Phase 8 v2 (2026-05-01) — Post-release behavior selon hospital_reason.
        // L'action est exécutée IMMÉDIATEMENT (pas juste set un flag) pour
        // que le joueur soit effectivement déplacé/incarcéré/mis en GAV
        // avant la notif.
        let postReleaseAction: 'normal' | 'redirect_prison' | 'gav_police' | 'held_added' = 'normal';
        const triggerPrisonRedirect = async (sentenceMs: number) => {
          // Utilise PrisonAssignmentService.assignPrison qui :
          //  • Trouve la prison la plus proche non saturée à 115%
          //  • Si saturé : pending_imprisonment_at = now + 9j (purge déférée)
          //  • Sinon : SET imprisoned_until + current_lat/lon → prison
          //  • Increment population, lazy POI, etc.
          // Reset held_remaining_ms après consommation.
          const days = Math.max(1, Math.ceil(sentenceMs / 86400000));
          try {
            const { PrisonAssignmentService } = await import('./prison-assignment.service');
            await PrisonAssignmentService.assignPrison(ph.player_id, days);
            // Consomme le held (la peine en attente est purgée par cette
            // incarcération — assignPrison gère imprisoned_until et le
            // cumul si held_remaining_ms est appliqué côté assignPrison
            // lui-même via une logique séparée ; ici on reset pour éviter
            // double comptage).
            await phRepo().update({ player_id: ph.player_id }, { held_remaining_ms: 0 });
          } catch (err) {
            console.error('[Hospital] assignPrison failed:', (err as Error).message);
          }
        };

        if (reason === 'gign') {
          if (hasPendingJudicial) {
            await triggerPrisonRedirect(heldRemainingMs);
            postReleaseAction = 'redirect_prison';
          } else {
            // Sortie normale + held +8j (dette de peine pour prochaine arrestation)
            const addedMs = heldGignDays * 24 * 3600 * 1000;
            await phRepo()
              .createQueryBuilder()
              .update()
              .set({ held_remaining_ms: () => `held_remaining_ms + ${addedMs}` })
              .where('player_id = :pid', { pid: ph.player_id })
              .execute();
            postReleaseAction = 'held_added';
          }
        } else if (reason === 'police') {
          // Trigger scene police (garde à vue)
          try {
            const { JudicialFlowService } = await import('./judicial-flow.service');
            const { CriminalRecord } = await import('../models/CriminalRecord');
            const crRepo = AppDataSource.getRepository(CriminalRecord);
            const lastRecord = await crRepo.findOne({
              where: { player_id: ph.player_id },
              order: { crime_date: 'DESC' },
            });
            if (lastRecord) {
              await JudicialFlowService.enterGardeAVue(ph.player_id, lastRecord.id);
              postReleaseAction = 'gav_police';
            }
          } catch (err) {
            console.error('[Hospital] Police GAV trigger failed:', (err as Error).message);
          }
        } else if (reason === 'combat' && hasPendingJudicial) {
          await triggerPrisonRedirect(heldRemainingMs);
          postReleaseAction = 'redirect_prison';
        }

        // Notif flavor selon postReleaseAction
        try {
          let flavor: string;
          switch (postReleaseAction) {
            case 'held_added':
              flavor = `Tu sors de l'hôpital, frais ${actualFee} ∞ prélevés. Le GIGN n'a pas oublié — ${heldGignDays} jours de peine en attente t'attendent à la prochaine arrestation.`;
              break;
            case 'gav_police':
              flavor = `Tu sors de l'hôpital. La police t'attendait — direction garde à vue.`;
              break;
            case 'redirect_prison':
              flavor = `Tu sors de l'hôpital, mais la justice n'a pas oublié. Direction prison pour purger la peine en attente.`;
              break;
            default:
              flavor = hasCard
                ? 'Tu sors de l\'hôpital. Frais couverts par ta carte santé. Bonne route.'
                : actualFee > 0
                  ? `Tu sors de l'hôpital. Frais ${actualFee} ∞ Light prélevés.`
                  : 'Tu sors de l\'hôpital. T\'avais rien sur toi — l\'admin a passé l\'éponge cette fois.';
          }
          await notifRepo().save(notifRepo().create({
            player_id: ph.player_id,
            type: 'system',
            title: 'Sortie d\'hôpital',
            message: flavor,
          }));
        } catch { /* silent */ }

        released++;
        totalFees += actualFee;
      } catch (err) {
        console.error('[Hospital] Release failed for', ph.player_id, ':', (err as Error).message);
      }
    }

    return { released, total_fees: totalFees };
  }

  /**
   * GET /api/hospital/status — Retourne le contexte hôpital pour le frontend
   * (countdown, missions, contacts, achat, frais à venir).
   */
  static async getHospitalStatus(playerId: string): Promise<{
    is_hospitalized: boolean;
    hospital_business_id: string | null;
    hospital_name: string | null;
    hospital_lat: number | null;
    hospital_lon: number | null;
    time_remaining_h: number;
    fee_due: number;
    has_health_card: boolean;
    can_buy_hospital: boolean;
    owns_this_hospital: boolean;
    healing_pts_remaining: number;
    bras_droit_active: boolean;
    /**
     * Phase 8 v2 narratives (2026-05-01) — true uniquement si la mission
     * H_01_REVEIL a été complétée AVEC `moral_choice='A'` (= "comment ça
     * va" + discussion) ET `moral_choice_2='A'` (= don 50% argent
     * accepté). Toute autre combinaison (A_B, B) → false : pas de bouton
     * évasion. Évite l'incohérence v1 où n'importe quel completed H_01
     * débloquait l'évasion.
     */
    escape_unlocked: boolean;
  }> {
    const ph = await phRepo().findOneBy({ player_id: playerId });
    const player = await playerRepo().findOneBy({ id: playerId });
    if (!ph || !player) {
      return {
        is_hospitalized: false,
        hospital_business_id: null,
        hospital_name: null,
        hospital_lat: null,
        hospital_lon: null,
        time_remaining_h: 0,
        fee_due: 0,
        has_health_card: false,
        can_buy_hospital: false,
        owns_this_hospital: false,
        healing_pts_remaining: 0,
        bras_droit_active: false,
        escape_unlocked: false,
      };
    }

    const now = new Date();
    const isHospitalized = !!ph.hospitalized_until && ph.hospitalized_until > now;
    const timeRemainingH = isHospitalized
      ? Math.max(0, (ph.hospitalized_until!.getTime() - now.getTime()) / 3600_000)
      : 0;

    // Hôpital actuel = celui le plus proche du hospital_lat/lon stocké
    let hospitalBusinessId: string | null = null;
    let hospitalName: string | null = null;
    if (player.hospital_lat && player.hospital_lon) {
      const biz = await businessRepo()
        .createQueryBuilder('b')
        .where('b.type = :type', { type: 'hospital' })
        .andWhere('ABS(b.location_lat - :lat) < 0.001', { lat: Number(player.hospital_lat) })
        .andWhere('ABS(b.location_lon - :lon) < 0.001', { lon: Number(player.hospital_lon) })
        .getOne();
      hospitalBusinessId = biz?.id ?? null;
      hospitalName = biz?.name ?? null;
    }

    const fee = await GameSettingsService.get<number>('hospital.exit_fee_default', 3000);
    const hasCard = await HealthService.hasCareCard(playerId);

    // Phase 8 v2 narratives (2026-05-01) — escape_unlocked = true uniquement
    // si H_01_REVEIL completed avec moral_choice='A' AND moral_choice_2='A'.
    // En v1 legacy (1 seul choix moral), moral_choice_2 sera NULL → faux
    // ce qui est cohérent avec la consigne user (don explicite requis).
    const { MissionProgress } = await import('../models/MissionProgress');
    const mpRepo = AppDataSource.getRepository(MissionProgress);
    const h01Progress = await mpRepo
      .createQueryBuilder('mp')
      .innerJoinAndSelect('mp.mission', 'm')
      .where('mp.player_id = :pid', { pid: playerId })
      .andWhere('mp.status = :st', { st: 'completed' })
      .andWhere('m.code = :code', { code: 'H_01_REVEIL' })
      .orderBy('mp.updated_at', 'DESC')
      .getOne();
    const escapeUnlocked = !!h01Progress
      && h01Progress.moral_choice === 'A'
      && h01Progress.moral_choice_2 === 'A';

    // Bras droit actif (réutilise pattern Phase 8.7)
    const { GangMember } = await import('../models/GangMember');
    const gmRepo = AppDataSource.getRepository(GangMember);
    const myMembership = await gmRepo.findOne({ where: { player_id: playerId } });
    let brasDroitActive = false;
    if (myMembership) {
      const bd = await gmRepo.findOne({
        where: { gang_id: myMembership.gang_id, role: 'bras_droit' as any },
      });
      brasDroitActive = !!bd && !bd.isHospitalized;
    }

    return {
      is_hospitalized: isHospitalized,
      hospital_business_id: hospitalBusinessId,
      hospital_name: hospitalName,
      hospital_lat: player.hospital_lat ? Number(player.hospital_lat) : null,
      hospital_lon: player.hospital_lon ? Number(player.hospital_lon) : null,
      time_remaining_h: Math.round(timeRemainingH * 10) / 10,
      fee_due: hasCard ? 0 : fee,
      has_health_card: hasCard,
      can_buy_hospital: !!player.can_buy_hospital_unlocked && !!hospitalBusinessId && hospitalBusinessId !== player.owned_hospital_business_id,
      owns_this_hospital: !!player.owned_hospital_business_id && player.owned_hospital_business_id === hospitalBusinessId,
      healing_pts_remaining: ph.healing_pts_remaining ?? 0,
      bras_droit_active: brasDroitActive,
      escape_unlocked: escapeUnlocked,
    };
  }

  /**
   * Achat de l'hôpital où le joueur est actuellement hospitalisé (35M ∞).
   * Requires : `can_buy_hospital_unlocked=true` (set par mission H_03).
   * Effet : transfère ownership du business + set Player.owned_hospital_business_id.
   */
  static async purchaseHospital(playerId: string): Promise<{ success: boolean; business_id: string; price: number }> {
    const player = await playerRepo().findOneBy({ id: playerId });
    if (!player) throw new Error('Joueur introuvable');
    if (!player.can_buy_hospital_unlocked) {
      throw new Error('Vous n\'avez pas la permission. Complétez la mission H_03 (rencontre directeur).');
    }

    const status = await HospitalService.getHospitalStatus(playerId);
    if (!status.hospital_business_id) {
      throw new Error('Aucun hôpital identifié pour l\'achat. Vous devez être hospitalisé.');
    }
    if (status.owns_this_hospital) {
      throw new Error('Vous possédez déjà cet hôpital.');
    }

    const price = await GameSettingsService.get<number>('hospital.purchase_price', 35000000);
    const paid = await PaymentService.debitMix({
      ownerType: 'player',
      ownerId: playerId,
      amount: price,
      category: 'property',
      description: `Achat hôpital ${status.hospital_name}`,
    });
    if (!paid.ok) {
      throw new Error(`Fonds insuffisants. Prix : ${price.toLocaleString('fr-FR')} ∞.`);
    }

    // Transfer ownership
    await businessRepo().update({ id: status.hospital_business_id }, { player_id: playerId });
    await playerRepo().update({ id: playerId }, { owned_hospital_business_id: status.hospital_business_id });

    try {
      await notifRepo().save(notifRepo().create({
        player_id: playerId,
        type: 'system',
        title: 'Hôpital acquis',
        message: `Tu possèdes désormais ${status.hospital_name}. Si on t'y envoie de force, tu sortiras direct.`,
      }));
    } catch { /* silent */ }

    return { success: true, business_id: status.hospital_business_id, price };
  }
}
