import { AppDataSource } from '../config/database';
import { NpcRecruitPool, NpcRecruitSlot } from '../models/NpcRecruitPool';
import { CartelRecruitPool } from '../models/CartelRecruitPool';
import { NpcRecruitService } from './npc-recruit.service';
import { CartelNpcRecruitService, CARTEL_GANGSTER_MAX } from './cartel-npc-recruit.service';

export type NpcPoolScope = 'player' | 'cartel';

export interface UnifiedPool {
  scope: NpcPoolScope;
  scope_id: string;
  size: number;
  has_elite: boolean;
  slots: NpcRecruitSlot[];
  refreshed_at: Date;
  next_refresh_at: Date;
}

/**
 * NpcPoolService — Phase 16 (2026-04-22), unification U6.
 *
 * Façade unifiée au-dessus de `NpcRecruitService` (player) et
 * `CartelNpcRecruitService` (cartel). Permet aux nouveaux callers
 * d'avoir une API unique `{getPool, refreshPool, recruit}` avec un
 * `scope` et un `scope_id`, sans avoir à choisir le service en amont.
 *
 * Les CRONs historiques (`NpcRecruit.refreshAllPools` /
 * `CartelNpcRecruit.refreshAllPools`) restent actifs et inchangés :
 * cette façade ne ré-implémente pas la logique métier, elle dispatche.
 *
 * Phase 17 (2026-05-04) — `getMinPoolSize` retiré (jamais consommé).
 * La garantie minimum est désormais portée par `rollPoolSize` dans
 * chaque service (anti-2-zéros : si pool précédent vide, force ≥1).
 */
export class NpcPoolService {
  /** Récupère le pool actuel pour un scope donné. */
  static async getPool(scope: NpcPoolScope, scopeId: string): Promise<UnifiedPool | null> {
    if (scope === 'player') {
      const p = await AppDataSource.getRepository(NpcRecruitPool)
        .findOne({ where: { player_id: scopeId } });
      if (!p) return null;
      return {
        scope: 'player',
        scope_id: scopeId,
        size: p.size,
        has_elite: p.has_elite,
        slots: p.slots,
        refreshed_at: p.refreshed_at,
        next_refresh_at: p.next_refresh_at,
      };
    }
    const c = await AppDataSource.getRepository(CartelRecruitPool)
      .findOne({ where: { cartel_id: scopeId } });
    if (!c) return null;
    return {
      scope: 'cartel',
      scope_id: scopeId,
      size: c.size,
      has_elite: c.has_elite,
      slots: c.slots,
      refreshed_at: c.refreshed_at,
      next_refresh_at: c.next_refresh_at,
    };
  }

  /** Refresh le pool (dispatch). */
  static async refreshPool(scope: NpcPoolScope, scopeId: string, allowElite = false): Promise<UnifiedPool> {
    if (scope === 'player') {
      const p = await NpcRecruitService.refreshPoolForPlayer(scopeId, allowElite);
      return {
        scope: 'player',
        scope_id: scopeId,
        size: p.size,
        has_elite: p.has_elite,
        slots: p.slots,
        refreshed_at: p.refreshed_at,
        next_refresh_at: p.next_refresh_at,
      };
    }
    const c = await CartelNpcRecruitService.refreshPoolForCartel(scopeId, allowElite);
    return {
      scope: 'cartel',
      scope_id: scopeId,
      size: c.size,
      has_elite: c.has_elite,
      slots: c.slots,
      refreshed_at: c.refreshed_at,
      next_refresh_at: c.next_refresh_at,
    };
  }

  /**
   * Recrute un candidat depuis le pool. Pour `cartel`, `actorPlayerId`
   * doit être admin ou officier du cartel.
   */
  static async recruit(
    scope: NpcPoolScope,
    scopeId: string,
    slotId: string,
    actorPlayerId: string,
  ): Promise<{ success: boolean; message: string }> {
    if (scope === 'player') {
      if (scopeId !== actorPlayerId) {
        return { success: false, message: 'Vous ne pouvez recruter que sur votre propre pool' };
      }
      return NpcRecruitService.recruitFromPool(actorPlayerId, slotId);
    }
    return CartelNpcRecruitService.recruitFromPool(scopeId, actorPlayerId, slotId);
  }

  /** Limite cartel (99) ré-exportée pour usage UI. */
  static readonly CARTEL_MAX = CARTEL_GANGSTER_MAX;
}
