/**
 * Phase 17 Phase 5 (2026-05-04) — PhoneAccessService.
 *
 * Détermine quel téléphone le joueur peut utiliser selon son état :
 *   • 'normal'  — téléphone perso classique (accès complet)
 *   • 'taulard' — MiniKom P1 (en prison + a acheté l'item)
 *   • 'none'    — pas de téléphone (en prison sans MiniKom, OU à
 *                 l'hôpital après police/GIGN)
 *
 * Consigne user verbatim 2026-05-04 :
 *   "En réalité en arrivant en prison : telephone à la fouille (item
 *    téléphone retiré (désacvtivé) temporairement jusqu'à la sortie.
 *    Il peut etre remplacé par un téléphone de taulard (...) si on
 *    obtient le téléphone de prison en mission (...). Hopital
 *    téléphone non disponible si police ou gign, mais si juste mort
 *    en combat ou accident téléphone disponible."
 */
import { AppDataSource } from '../config/database';
import { PlayerHealth } from '../models/PlayerHealth';
import { PlayerInventory } from '../models/PlayerInventory';

const phRepo = () => AppDataSource.getRepository(PlayerHealth);
const inventoryRepo = () => AppDataSource.getRepository(PlayerInventory);

export type PhoneAccess = 'normal' | 'taulard' | 'none';

export interface PhoneAccessResult {
  access: PhoneAccess;
  reason: string;
  is_imprisoned: boolean;
  is_hospitalized: boolean;
  hospital_reason: string | null;
  has_prison_phone: boolean;
  /**
   * Phase 17.1 (2026-05-05) — Drapeau "le joueur a un bras droit gang
   * actif". L'app Phone "Gestion Gang" n'apparaît que si true. La règle
   * exacte côté backend est :
   *   • Le joueur est leader d'un gang OU bras_droit
   *   • ET le gang a un member role='bras_droit' actif (un NPC promu)
   * → permet de dispatcher des ordres via téléphone même si le leader
   *   est en prison/hospitalisé (consigne user verbatim Phase 17 Phase 5).
   */
  has_bras_droit_gang: boolean;
  /**
   * Phase 17.1 (2026-05-05) — Drapeau "le cartel du joueur a au moins
   * un underboss assigné" (CartelMember is_admin=true ET pas le fondateur,
   * càd gang_id !== cartel.leader_gang_id). L'app Phone "Gestion Cartel"
   * n'apparaît que si true.
   */
  has_underboss_cartel: boolean;
}

export class PhoneAccessService {

  /**
   * Retourne l'accès téléphonique courant du joueur.
   *
   * Logique :
   *   1. Si imprisoned :
   *      • has MiniKom on_person → 'taulard'
   *      • sinon → 'none' (téléphone confisqué à la fouille)
   *   2. Si hospitalized :
   *      • hospital_reason ∈ {'police', 'gign'} → 'none' (sous garde)
   *      • sinon (combat normal, accident, overdose…) → 'normal'
   *   3. Sinon → 'normal'
   */
  static async getAccess(playerId: string): Promise<PhoneAccessResult> {
    const ph = await phRepo().findOneBy({ player_id: playerId });
    const now = new Date();

    const imprisonedUntil = ph?.imprisoned_until ? new Date(ph.imprisoned_until) : null;
    const isImprisoned = !!imprisonedUntil && imprisonedUntil.getTime() > now.getTime();

    const hospitalizedUntil = ph?.hospitalized_until ? new Date(ph.hospitalized_until) : null;
    const isHospitalized = !!hospitalizedUntil && hospitalizedUntil.getTime() > now.getTime();
    const hospitalReason = ph?.hospital_reason ?? null;

    // Phase 17.1 (2026-05-05) — Drapeaux Gestion Gang/Cartel.
    // Calculés UNE FOIS ici puis injectés dans tous les chemins de retour.
    const flags = await PhoneAccessService.computeManagementFlags(playerId);

    // 1. Prison
    if (isImprisoned) {
      const miniKom = await inventoryRepo().findOne({
        where: {
          player_id: playerId,
          item_subtype: 'minikom_p1',
          storage_condition: 'on_person',
        },
      });
      const hasPrisonPhone = !!miniKom;
      return {
        access: hasPrisonPhone ? 'taulard' : 'none',
        reason: hasPrisonPhone
          ? 'Téléphone perso confisqué à la fouille. MiniKom P1 disponible.'
          : 'Téléphone confisqué à la fouille en prison. Achète un MiniKom P1 à la cantine pour communiquer.',
        is_imprisoned: true,
        is_hospitalized: isHospitalized,
        hospital_reason: hospitalReason,
        has_prison_phone: hasPrisonPhone,
        ...flags,
      };
    }

    // 2. Hospital
    if (isHospitalized) {
      // Téléphone confisqué si police OU GIGN entry (le joueur est sous
      // garde, pas dans une chambre normale)
      const isUnderGuard = hospitalReason === 'police' || hospitalReason === 'gign';
      if (isUnderGuard) {
        return {
          access: 'none',
          reason: hospitalReason === 'gign'
            ? 'Sous garde GIGN à l\'hôpital — téléphone confisqué.'
            : 'Sous garde policière à l\'hôpital — téléphone confisqué.',
          is_imprisoned: false,
          is_hospitalized: true,
          hospital_reason: hospitalReason,
          has_prison_phone: false,
          ...flags,
        };
      }
      // Combat normal / accident / overdose → téléphone OK
      return {
        access: 'normal',
        reason: 'Hospitalisé sans garde — téléphone disponible.',
        is_imprisoned: false,
        is_hospitalized: true,
        hospital_reason: hospitalReason,
        has_prison_phone: false,
        ...flags,
      };
    }

    // 3. Default : normal
    return {
      access: 'normal',
      reason: 'Téléphone perso disponible.',
      is_imprisoned: false,
      is_hospitalized: false,
      hospital_reason: null,
      has_prison_phone: false,
      ...flags,
    };
  }

  /**
   * Phase 17.1 (2026-05-05) — Calcule les drapeaux Gestion Gang/Cartel
   * pour le téléphone (apps visibles si bras_droit/underboss assigné).
   *
   *   • has_bras_droit_gang : le gang du joueur a un member avec
   *     role='bras_droit' actif. Le bras droit lui-même est inclus
   *     dans cette catégorie (s'il accède au tel d'un autre, peu probable).
   *   • has_underboss_cartel : le cartel du joueur a au moins 1
   *     CartelMember is_admin=true dont gang_id !== cartel.leader_gang_id
   *     (donc un admin promu underboss, pas le fondateur).
   */
  private static async computeManagementFlags(playerId: string): Promise<{
    has_bras_droit_gang: boolean;
    has_underboss_cartel: boolean;
  }> {
    const { GangMember } = await import('../models/GangMember');
    const { CartelMember } = await import('../models/CartelMember');
    const { Cartel } = await import('../models/Cartel');

    // Gang du joueur
    const gmRepo = AppDataSource.getRepository(GangMember);
    const myGm = await gmRepo.findOne({ where: { player_id: playerId } });
    let has_bras_droit_gang = false;
    if (myGm?.gang_id) {
      const bd = await gmRepo.findOne({
        where: { gang_id: myGm.gang_id, role: 'bras_droit' as any },
      });
      has_bras_droit_gang = !!bd;
    }

    // Cartel du joueur
    let has_underboss_cartel = false;
    if (myGm?.gang_id) {
      const cmRepo = AppDataSource.getRepository(CartelMember);
      const myCm = await cmRepo.findOne({
        where: { gang_id: myGm.gang_id, status: 'active' as any },
      });
      if (myCm?.cartel_id) {
        const cartel = await AppDataSource.getRepository(Cartel)
          .findOne({ where: { id: myCm.cartel_id } });
        if (cartel) {
          // Admin non fondateur = underboss
          const underbosses = await cmRepo.find({
            where: { cartel_id: myCm.cartel_id, is_admin: true as any, status: 'active' as any },
          });
          has_underboss_cartel = underbosses.some((u) => u.gang_id !== cartel.leader_gang_id);
        }
      }
    }

    return { has_bras_droit_gang, has_underboss_cartel };
  }
}
