/**
 * Phase 17 (2026-05-04) — DetectiveService.
 *
 * Génère un rapport hebdomadaire pour chaque attachment role='detective'
 * dont next_report_at <= NOW. Algorithme complet selon la spec user :
 *
 *   1. Salaire : payé chaque jour par cron daily (out of scope ici,
 *      cf SpecialistDailyPaymentService — Phase 2d).
 *   2. Cible stock : [400 × N, 2000 × N] ∞ (N = skill du détective).
 *   3. Si pool vide pour ce skill → downgrade au palier N-1, rembourse
 *      la différence (paye_jour - 10×(N-1)) × 7. Récursif jusqu'à N=1.
 *   4. Si pool vide partout → remboursement intégral du salaire hebdo.
 *      Notif "J'ai eu beau creuser, on dirait que tout le monde est à
 *      paye ! Je tiens au courant si ça a bougé dans une semaine."
 *      L'attachment reste actif (re-tente la semaine d'après).
 *   5. Si pool trouvé : tirage sub-tranche (petit/moyen/gros) selon paye :
 *        p = (paye_jour - 10×N) / (10×N)  ∈ [0, 1]
 *        % petit = 50 - 30 × p
 *        % moyen = 30 (constant)
 *        % gros  = 20 + 30 × p
 *      Tier sélectionné, on pick un POI dont stock_value ∈ tier_range.
 *      Priorité aux stocks > 1500 (ROI joueur).
 *   6. INSERT poi_revelations (TTL +7j) + notif détaillée.
 *   7. att.next_report_at = NOW() + 7j ; att.last_report_at = NOW().
 */

import { AppDataSource } from '../config/database';
import { Specialist } from '../models/Specialist';
import { SpecialistAttachment, SpecialistOwnerType } from '../models/SpecialistAttachment';
import { POIRevelation } from '../models/POIRevelation';
import { NpcStockedPOI } from '../models/NpcStockedPOI';
import { Notification } from '../models/Notification';
import { PaymentService } from './payment.service';

const specRepo = () => AppDataSource.getRepository(Specialist);
const attRepo = () => AppDataSource.getRepository(SpecialistAttachment);
const revRepo = () => AppDataSource.getRepository(POIRevelation);
const npcPoiRepo = () => AppDataSource.getRepository(NpcStockedPOI);
const notifRepo = () => AppDataSource.getRepository(Notification);

/** Représente un POI avec stock, agrégé pour le sourcing détective. */
export interface StockedPOICandidate {
  poi_type: 'warehouse' | 'business' | 'point_de_deal' | 'entrepot';
  poi_id: string;
  owner_player_id: string;
  owner_alias: string;          // nom affiché du propriétaire (NPC ou joueur)
  owner_chaleur: number;
  total_stock_value: number;     // ∞ revente approximative
  stock_summary: string;         // résumé items pour le rapport
  position_lat: number | null;
  position_lon: number | null;
}

export class DetectiveService {

  /**
   * CRON weekly — process tous les attachments dont next_report_at <= NOW.
   */
  static async processDueReports(): Promise<{ processed: number; success: number; refunded: number }> {
    const due = await attRepo()
      .createQueryBuilder('a')
      .innerJoinAndSelect('a.specialist', 's')
      .where('a.is_active = true')
      .andWhere('s.role = :r', { r: 'detective' })
      .andWhere('a.next_report_at IS NOT NULL')
      .andWhere('a.next_report_at <= NOW()')
      .getMany();

    let processed = 0, success = 0, refunded = 0;
    for (const att of due) {
      try {
        const result = await DetectiveService.runWeeklyReport(att.id);
        processed++;
        if (result.kind === 'reveal') success++;
        else refunded++;
      } catch (err) {
        console.error('[Detective] runWeeklyReport failed for', att.id, ':', (err as Error).message);
      }
    }
    return { processed, success, refunded };
  }

  /**
   * Génère un rapport pour un attachment spécifique (1 seul appel,
   * idempotent vis-à-vis de next_report_at).
   */
  static async runWeeklyReport(attachmentId: string): Promise<
    | { kind: 'reveal'; revelation_id: string; poi_id: string; effective_skill: number }
    | { kind: 'no_pistes'; refund_total: number }
  > {
    const att = await attRepo().findOne({
      where: { id: attachmentId },
      relations: ['specialist'],
    });
    if (!att) throw new Error('Attachment introuvable');
    if (!att.is_active) throw new Error('Attachment inactif');
    if (att.specialist.role !== 'detective') {
      throw new Error('runWeeklyReport ne s\'applique qu\'aux détectives');
    }

    const skill = att.specialist.skill_level;
    const paye_jour = att.chosen_daily_rate ?? (15 * skill); // fallback médian
    const paye_hebdo = paye_jour * 7;

    // Recherche descendante (downgrade si pool vide)
    let totalRefunded = 0;
    for (let currentSkill = skill; currentSkill >= 1; currentSkill--) {
      const stockLo = 400 * currentSkill;
      const stockHi = 2000 * currentSkill;

      const candidates = await DetectiveService.findEligibleStockedPOIs({
        excludeOwnerType: att.owner_type,
        excludeOwnerId: att.owner_id,
        stockValueMin: stockLo,
        stockValueMax: stockHi,
      });

      if (candidates.length === 0) {
        if (currentSkill < skill) {
          // Downgrade : rembourse la différence (paye_jour - 10×N-1) × 7
          const refundAmount = Math.max(0, (paye_jour - 10 * (currentSkill - 1)) * 7);
          if (refundAmount > 0) {
            await DetectiveService.refundOwner(att, refundAmount, 'detective_downgrade');
            totalRefunded += refundAmount;
          }
        }
        continue; // try lower skill
      }

      // Pool non vide : tirer sub-tranche selon paye
      const p = Math.max(0, Math.min(1, (paye_jour - 10 * currentSkill) / (10 * currentSkill)));
      const tierSize = (stockHi - stockLo) / 3;
      const pctPetit = 50 - 30 * p;
      const pctMoyen = 30;
      // pctGros = 20 + 30 × p (déduit)

      const r = Math.random() * 100;
      let targetMin: number;
      let targetMax: number;
      if (r < pctPetit) {
        targetMin = stockLo;
        targetMax = stockLo + tierSize;
      } else if (r < pctPetit + pctMoyen) {
        targetMin = stockLo + tierSize;
        targetMax = stockLo + 2 * tierSize;
      } else {
        targetMin = stockLo + 2 * tierSize;
        targetMax = stockHi;
      }

      // Filter candidates dans la sub-tranche
      let inTier = candidates.filter(
        (c) => c.total_stock_value >= targetMin && c.total_stock_value <= targetMax,
      );
      // Fallback : si tier vide, on prend tout le pool éligible
      if (inTier.length === 0) inTier = candidates;

      // Priorité aux stocks > 1500 (ROI joueur)
      const priority = inTier.filter((c) => c.total_stock_value > 1500);
      const pool = priority.length > 0 ? priority : inTier;

      const picked = pool[Math.floor(Math.random() * pool.length)];

      // Insert revelation
      const revelation = await revRepo().save(revRepo().create({
        owner_type: att.owner_type as 'player' | 'gang' | 'cartel',
        owner_id: att.owner_id,
        poi_type: picked.poi_type,
        poi_id: picked.poi_id,
        source_attachment_id: att.id,
        details_json: {
          total_stock_value: picked.total_stock_value,
          stock_summary: picked.stock_summary,
          owner_alias: picked.owner_alias,
          owner_chaleur: picked.owner_chaleur,
          effective_skill: currentSkill,
          tier_label: r < pctPetit ? 'petit' : r < pctPetit + pctMoyen ? 'moyen' : 'gros',
        },
        revealed_at: new Date(),
        revealed_until: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
      }));

      // Update attachment
      att.next_report_at = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
      att.last_report_at = new Date();
      await attRepo().save(att);

      // Notif rapport détaillé
      const notifTitle = `Rapport ${att.specialist.name}`;
      const notifMsg =
        `Repère localisé : ${picked.poi_type} de ${picked.owner_alias} ` +
        `(chaleur ${picked.owner_chaleur}). Stock estimé ${picked.total_stock_value.toLocaleString('fr-FR')} ∞. ` +
        `Détail : ${picked.stock_summary}. Visible 7 jours sur ta carte.`;
      await DetectiveService.notifyOwner(att, 'system', notifTitle, notifMsg);

      return {
        kind: 'reveal',
        revelation_id: revelation.id,
        poi_id: picked.poi_id,
        effective_skill: currentSkill,
      };
    }

    // Boucle terminée sans résultat = rien partout : remboursement intégral
    const fullRefund = paye_hebdo;
    await DetectiveService.refundOwner(att, fullRefund, 'detective_no_pistes');
    totalRefunded += fullRefund;

    att.next_report_at = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
    await attRepo().save(att);

    await DetectiveService.notifyOwner(
      att,
      'system',
      `Aucune piste — ${att.specialist.name}`,
      "J'ai eu beau creuser, on dirait que tout le monde est à paye ! Je tiens au courant si ça a bougé dans une semaine.",
    );

    return { kind: 'no_pistes', refund_total: totalRefunded };
  }

  /**
   * CRON cleanup — supprime les poi_revelations expirées (revealed_until < NOW).
   * Gardé léger : 1 query DELETE.
   */
  static async cleanupExpiredRevelations(): Promise<{ deleted: number }> {
    const result = await revRepo()
      .createQueryBuilder()
      .delete()
      .where('revealed_until < NOW()')
      .execute();
    const deleted = result.affected ?? 0;
    if (deleted > 0) {
      console.log(`[Detective] cleaned ${deleted} expired POI revelations`);
    }
    return { deleted };
  }

  /**
   * GET — Liste les POI revelations actives pour un owner (player/gang/cartel).
   * Utilisé par le frontend pour afficher les POIs sur la carte avec un
   * badge "Enquêteur" et le détail dans une lightbox.
   */
  static async listActiveRevelations(
    ownerType: SpecialistOwnerType,
    ownerId: string,
  ): Promise<POIRevelation[]> {
    return revRepo()
      .createQueryBuilder('r')
      .where('r.owner_type = :t AND r.owner_id = :id', { t: ownerType, id: ownerId })
      .andWhere('r.revealed_until > NOW()')
      .orderBy('r.revealed_at', 'DESC')
      .getMany();
  }

  /**
   * Phase 17.2 finition (2026-05-06) — Variante enrichie : résout name/lat/lon
   * du POI source selon son `poi_type`. Permet au frontend d'afficher le
   * rapport sans refaire le join côté UI.
   *
   * Sources de résolution :
   *   • npc_stocked_poi → NpcStockedPOI.{name, lat, lon}
   *   • business        → Business.{name, location_lat, location_lon}
   *   • warehouse       → Warehouse.{name, location_lat, location_lon}
   *   • point_de_deal   → Residence.{name, location_lat, location_lon}
   *   • hideout         → Residence (planque) idem
   *
   * Si la résolution échoue (POI supprimé entre-temps), poi_meta est null
   * mais la révélation reste retournée pour audit.
   */
  static async listActiveRevelationsEnriched(
    ownerType: SpecialistOwnerType,
    ownerId: string,
  ): Promise<Array<POIRevelation & {
    poi_meta: {
      name: string | null;
      lat: number | null;
      lon: number | null;
      poi_type_label: string;
      is_npc: boolean;
    } | null;
  }>> {
    const reveals = await DetectiveService.listActiveRevelations(ownerType, ownerId);
    if (reveals.length === 0) return [];

    // Group poi_id par poi_type pour faire des fetch IN (..) groupés
    const idsByType = new Map<string, string[]>();
    for (const r of reveals) {
      if (!idsByType.has(r.poi_type)) idsByType.set(r.poi_type, []);
      idsByType.get(r.poi_type)!.push(r.poi_id);
    }

    const meta = new Map<string, { name: string | null; lat: number | null; lon: number | null }>();

    // Lazy-import pour éviter les cycles
    const [{ Business }, { Warehouse }, { Residence }] = await Promise.all([
      import('../models/Business'),
      import('../models/Warehouse'),
      import('../models/Residence'),
    ]);

    await Promise.all(Array.from(idsByType.entries()).map(async ([type, ids]) => {
      if (type === 'npc_stocked_poi' || type === 'entrepot') {
        const rows = await npcPoiRepo().createQueryBuilder('p')
          .select(['p.id AS id', 'p.name AS name', 'p.lat AS lat', 'p.lon AS lon'])
          .where('p.id IN (:...ids)', { ids })
          .getRawMany<{ id: string; name: string; lat: string | number; lon: string | number }>();
        for (const r of rows) meta.set(r.id, { name: r.name, lat: Number(r.lat), lon: Number(r.lon) });
      } else if (type === 'business') {
        const rows = await AppDataSource.getRepository(Business)
          .createQueryBuilder('b')
          .select(['b.id AS id', 'b.name AS name', 'b.location_lat AS lat', 'b.location_lon AS lon'])
          .where('b.id IN (:...ids)', { ids })
          .getRawMany<{ id: string; name: string; lat: string | number | null; lon: string | number | null }>();
        for (const r of rows) meta.set(r.id, {
          name: r.name,
          lat: r.lat != null ? Number(r.lat) : null,
          lon: r.lon != null ? Number(r.lon) : null,
        });
      } else if (type === 'warehouse') {
        const rows = await AppDataSource.getRepository(Warehouse)
          .createQueryBuilder('w')
          .select(['w.id AS id', 'w.name AS name', 'w.location_lat AS lat', 'w.location_lon AS lon'])
          .where('w.id IN (:...ids)', { ids })
          .getRawMany<{ id: string; name: string; lat: string | number | null; lon: string | number | null }>();
        for (const r of rows) meta.set(r.id, {
          name: r.name,
          lat: r.lat != null ? Number(r.lat) : null,
          lon: r.lon != null ? Number(r.lon) : null,
        });
      } else if (type === 'point_de_deal' || type === 'hideout') {
        const rows = await AppDataSource.getRepository(Residence)
          .createQueryBuilder('r')
          .select(['r.id AS id', 'r.name AS name', 'r.location_lat AS lat', 'r.location_lon AS lon'])
          .where('r.id IN (:...ids)', { ids })
          .getRawMany<{ id: string; name: string; lat: string | number | null; lon: string | number | null }>();
        for (const row of rows) meta.set(row.id, {
          name: row.name,
          lat: row.lat != null ? Number(row.lat) : null,
          lon: row.lon != null ? Number(row.lon) : null,
        });
      }
    }));

    const POI_TYPE_LABEL: Record<string, string> = {
      npc_stocked_poi: 'POI gardé (NPC)',
      entrepot: 'Entrepôt gardé (NPC)',
      business: 'Commerce joueur',
      warehouse: 'Entrepôt joueur',
      point_de_deal: 'Point de deal joueur',
      hideout: 'Planque joueur',
    };
    const NPC_TYPES = new Set(['npc_stocked_poi', 'entrepot']);

    return reveals.map((r) => {
      const m = meta.get(r.poi_id);
      return {
        ...r,
        poi_meta: m
          ? {
              name: m.name,
              lat: m.lat,
              lon: m.lon,
              poi_type_label: POI_TYPE_LABEL[r.poi_type] || r.poi_type,
              is_npc: NPC_TYPES.has(r.poi_type),
            }
          : null,
      };
    });
  }

  // ─── Helpers privés ────────────────────────────────────────────────

  /**
   * Trouve les POIs avec stock dans la fourchette de valeur donnée,
   * éligibles à révélation par un détective.
   *
   * Phase 17.1 (2026-05-05) — Étendu aux POIs joueurs (warehouse + business)
   * en plus des npc_stocked_pois seedés.
   *
   * Filtres communs :
   *   • owner.chaleur >= 50 (consigne user — info issue de joueurs "qui
   *     attirent l'attention" : balance/police/heat)
   *   • stock_value ∈ [stockValueMin, stockValueMax]
   *   • Owner != excludeOwnerId (le détective ne révèle pas ses propres POIs)
   *   • Exclu si déjà dans poi_revelations actives pour cet owner
   *
   * Sources concaténées :
   *   1. npc_stocked_pois (210 POIs seedés, valeur exacte)
   *   2. Business player_id != excludeOwnerId
   *      → stock_value = cash_register + illegal_cash_register +
   *        current_stock_kg × 50 (heuristique : 50 ∞/kg moyen toutes drogues)
   *   3. Warehouse player_id != excludeOwnerId
   *      → stock_value = current_fill × 100 (heuristique : 100 ∞/unit_capacité)
   *
   * Pour le scope du détective :
   *   • scope='player' → exclude excludeOwnerId direct
   *   • scope='gang' → exclude tous les members du gang
   *   • scope='cartel' → exclude tous les members des gangs du cartel
   */
  private static async findEligibleStockedPOIs(args: {
    excludeOwnerType: SpecialistOwnerType;
    excludeOwnerId: string;
    stockValueMin: number;
    stockValueMax: number;
  }): Promise<StockedPOICandidate[]> {
    const { excludeOwnerType, excludeOwnerId, stockValueMin, stockValueMax } = args;

    // Récupère les poi_id déjà révélés ACTIFS pour cet owner (éviter doublon)
    const activeRevealsRows = await revRepo()
      .createQueryBuilder('r')
      .select('r.poi_id', 'poi_id')
      .where('r.owner_type = :t AND r.owner_id = :id', { t: excludeOwnerType, id: excludeOwnerId })
      .andWhere('r.revealed_until > NOW()')
      .getRawMany();
    const excludedPoiIds = activeRevealsRows.map((r) => r.poi_id as string);

    // Phase 17.1 — Liste des player_id à exclure (le détective ne se révèle
    // pas lui-même ni les members de son scope)
    const excludePlayerIds = await DetectiveService.resolveExcludePlayerIds(
      excludeOwnerType, excludeOwnerId,
    );

    // ─── Source 1 : npc_stocked_pois ───
    const qbNpc = npcPoiRepo()
      .createQueryBuilder('p')
      .where('p.is_active = true')
      .andWhere('p.owner_chaleur >= :hMin', { hMin: 50 })
      .andWhere('p.total_stock_value BETWEEN :sMin AND :sMax', {
        sMin: stockValueMin,
        sMax: stockValueMax,
      });
    if (excludedPoiIds.length > 0) {
      qbNpc.andWhere('p.id NOT IN (:...excluded)', { excluded: excludedPoiIds });
    }
    const npcPois = await qbNpc.getMany();
    const candidates: StockedPOICandidate[] = npcPois.map((p) => ({
      poi_type: p.poi_kind,
      poi_id: p.id,
      owner_player_id: 'npc',
      owner_alias: p.owner_alias,
      owner_chaleur: p.owner_chaleur,
      total_stock_value: p.total_stock_value,
      stock_summary: p.stock_summary,
      position_lat: Number(p.lat),
      position_lon: Number(p.lon),
    }));

    // ─── Source 2 : Business player_id != excludePlayerIds ───
    // Stock value = cash_register + illegal_cash_register + current_stock_kg × 50
    const { Business } = await import('../models/Business');
    const businessQb = AppDataSource.getRepository(Business)
      .createQueryBuilder('b')
      .innerJoin('player_gauges', 'pg', 'pg.player_id = b.player_id')
      .innerJoin('players', 'pl', 'pl.id = b.player_id')
      .select([
        'b.id AS id',
        'b.name AS name',
        'b.location_lat AS lat',
        'b.location_lon AS lon',
        'b.cash_register AS cash_register',
        'b.illegal_cash_register AS illegal_cash_register',
        'b.current_stock_kg AS current_stock_kg',
        'b.player_id AS player_id',
        'pl.character_name AS character_name',
        'pl.username AS username',
        'pg.chaleur AS chaleur',
      ])
      .where('b.player_id IS NOT NULL')
      .andWhere('pg.chaleur >= :hMin', { hMin: 50 })
      .andWhere('(b.cash_register + b.illegal_cash_register + b.current_stock_kg * 50) BETWEEN :sMin AND :sMax', {
        sMin: stockValueMin,
        sMax: stockValueMax,
      });
    if (excludePlayerIds.length > 0) {
      businessQb.andWhere('b.player_id NOT IN (:...excludedPlayers)', { excludedPlayers: excludePlayerIds });
    }
    if (excludedPoiIds.length > 0) {
      businessQb.andWhere('b.id NOT IN (:...excluded)', { excluded: excludedPoiIds });
    }
    const businessRows = await businessQb.getRawMany();
    for (const r of businessRows) {
      const stockValue = Number(r.cash_register || 0) + Number(r.illegal_cash_register || 0) + Number(r.current_stock_kg || 0) * 50;
      const ownerName = r.character_name || r.username || 'inconnu';
      const stockKg = Number(r.current_stock_kg || 0);
      const cashTotal = Number(r.cash_register || 0) + Number(r.illegal_cash_register || 0);
      candidates.push({
        poi_type: 'business',
        poi_id: r.id,
        owner_player_id: r.player_id,
        owner_alias: ownerName,
        owner_chaleur: Number(r.chaleur || 0),
        total_stock_value: stockValue,
        stock_summary: `${r.name} — caisse ${cashTotal.toLocaleString('fr-FR')} ∞${stockKg > 0 ? ` + stock ${stockKg} kg` : ''}`,
        position_lat: r.lat ? Number(r.lat) : null,
        position_lon: r.lon ? Number(r.lon) : null,
      });
    }

    // ─── Source 4 : Residence avec point de deal actif ───
    // Phase 17.2 (2026-05-05) — Le `point_de_deal` joueur est représenté
    // dans la table `residences` avec deal_spot_active=true. Stock value
    // approximatif = deal_spot_heat × 100 (heuristique : la heat
    // accumulée est proportionnelle au revenu généré non encore extorqué).
    const { Residence } = await import('../models/Residence');
    const dealSpotQb = AppDataSource.getRepository(Residence)
      .createQueryBuilder('r')
      .innerJoin('player_gauges', 'pg', 'pg.player_id = r.player_id')
      .innerJoin('players', 'pl', 'pl.id = r.player_id')
      .select([
        'r.id AS id',
        'r.name AS name',
        'r.location_lat AS lat',
        'r.location_lon AS lon',
        'r.deal_spot_drug AS deal_spot_drug',
        'r.deal_spot_heat AS deal_spot_heat',
        'r.player_id AS player_id',
        'pl.character_name AS character_name',
        'pl.username AS username',
        'pg.chaleur AS chaleur',
      ])
      .where('r.deal_spot_active = true')
      .andWhere('pg.chaleur >= :hMin', { hMin: 50 })
      .andWhere('(r.deal_spot_heat * 100) BETWEEN :sMin AND :sMax', {
        sMin: stockValueMin,
        sMax: stockValueMax,
      });
    if (excludePlayerIds.length > 0) {
      dealSpotQb.andWhere('r.player_id NOT IN (:...excludedPlayers)', { excludedPlayers: excludePlayerIds });
    }
    if (excludedPoiIds.length > 0) {
      dealSpotQb.andWhere('r.id NOT IN (:...excluded)', { excluded: excludedPoiIds });
    }
    const dealSpotRows = await dealSpotQb.getRawMany();
    for (const r of dealSpotRows) {
      const stockValue = Number(r.deal_spot_heat || 0) * 100;
      const ownerName = r.character_name || r.username || 'inconnu';
      const drug = r.deal_spot_drug || 'drogue';
      candidates.push({
        poi_type: 'point_de_deal',
        poi_id: r.id,
        owner_player_id: r.player_id,
        owner_alias: ownerName,
        owner_chaleur: Number(r.chaleur || 0),
        total_stock_value: stockValue,
        stock_summary: `Point de deal (${drug}) — heat ${r.deal_spot_heat}/100`,
        position_lat: r.lat ? Number(r.lat) : null,
        position_lon: r.lon ? Number(r.lon) : null,
      });
    }

    // ─── Source 3 : Warehouse player_id != excludePlayerIds ───
    // Stock value = current_fill × 100 (heuristique simple)
    const { Warehouse } = await import('../models/Warehouse');
    const warehouseQb = AppDataSource.getRepository(Warehouse)
      .createQueryBuilder('w')
      .innerJoin('player_gauges', 'pg', 'pg.player_id = w.player_id')
      .innerJoin('players', 'pl', 'pl.id = w.player_id')
      .select([
        'w.id AS id',
        'w.name AS name',
        'w.location_lat AS lat',
        'w.location_lon AS lon',
        'w.current_fill AS current_fill',
        'w.type AS type',
        'w.player_id AS player_id',
        'pl.character_name AS character_name',
        'pl.username AS username',
        'pg.chaleur AS chaleur',
      ])
      .where('w.current_fill > 0')
      .andWhere('pg.chaleur >= :hMin', { hMin: 50 })
      .andWhere('(w.current_fill * 100) BETWEEN :sMin AND :sMax', {
        sMin: stockValueMin,
        sMax: stockValueMax,
      });
    if (excludePlayerIds.length > 0) {
      warehouseQb.andWhere('w.player_id NOT IN (:...excludedPlayers)', { excludedPlayers: excludePlayerIds });
    }
    if (excludedPoiIds.length > 0) {
      warehouseQb.andWhere('w.id NOT IN (:...excluded)', { excluded: excludedPoiIds });
    }
    const warehouseRows = await warehouseQb.getRawMany();
    for (const r of warehouseRows) {
      const stockValue = Number(r.current_fill || 0) * 100;
      const ownerName = r.character_name || r.username || 'inconnu';
      candidates.push({
        poi_type: 'warehouse',
        poi_id: r.id,
        owner_player_id: r.player_id,
        owner_alias: ownerName,
        owner_chaleur: Number(r.chaleur || 0),
        total_stock_value: stockValue,
        stock_summary: `${r.name} (${r.type}) — capacité utilisée ${r.current_fill} unités`,
        position_lat: r.lat ? Number(r.lat) : null,
        position_lon: r.lon ? Number(r.lon) : null,
      });
    }

    return candidates;
  }

  /**
   * Phase 17.1 (2026-05-05) — Résout la liste des player_id à exclure
   * du sourcing détective selon le scope de l'attachment.
   *
   *   • scope='player' → [excludeOwnerId]
   *   • scope='gang'   → tous les members du gang
   *   • scope='cartel' → tous les members des gangs du cartel
   */
  private static async resolveExcludePlayerIds(
    ownerType: SpecialistOwnerType,
    ownerId: string,
  ): Promise<string[]> {
    if (ownerType === 'player') return [ownerId];

    if (ownerType === 'gang') {
      const { GangMember } = await import('../models/GangMember');
      const members = await AppDataSource.getRepository(GangMember).find({
        where: { gang_id: ownerId },
        select: { player_id: true },
      });
      return members.map((m) => m.player_id);
    }

    if (ownerType === 'cartel') {
      const { CartelMember } = await import('../models/CartelMember');
      const { GangMember } = await import('../models/GangMember');
      const cartelMembers = await AppDataSource.getRepository(CartelMember).find({
        where: { cartel_id: ownerId, status: 'active' as any },
      });
      const gangIds = cartelMembers.map((cm) => cm.gang_id);
      if (gangIds.length === 0) return [];
      const gMembers = await AppDataSource.getRepository(GangMember).find({
        where: gangIds.map((gid) => ({ gang_id: gid })),
        select: { player_id: true },
      });
      return gMembers.map((m) => m.player_id);
    }

    return [];
  }

  /** Crédite l'owner du remboursement (player/gang/cartel treasury). */
  private static async refundOwner(
    att: SpecialistAttachment,
    amount: number,
    _reason: string,
  ): Promise<void> {
    if (amount <= 0) return;
    await PaymentService.credit({
      ownerType: att.owner_type as 'player' | 'gang' | 'cartel',
      ownerId: att.owner_id,
      amount,
      currency: 'shadow',
    });
  }

  /**
   * Phase 17.1 (2026-05-05) — Notif l'owner d'un attachment détective.
   *
   *   • scope='player' → 1 notif au player_id
   *   • scope='gang'   → notif au leader + bras_droit (s'il existe)
   *   • scope='cartel' → notif à tous les admins (is_admin=true) du cartel
   *     via leur primary_player_id
   */
  private static async notifyOwner(
    att: SpecialistAttachment,
    type: 'system',
    title: string,
    message: string,
  ): Promise<void> {
    try {
      const recipients = await DetectiveService.resolveNotifRecipients(att);
      if (recipients.length === 0) {
        console.log(`[Detective] notifyOwner — aucun destinataire pour ${att.owner_type}/${att.owner_id}`);
        return;
      }
      const rows = recipients.map((pid) => notifRepo().create({
        player_id: pid,
        type,
        title,
        message,
      }));
      await notifRepo().save(rows);
    } catch (err) {
      console.error('[Detective] notifyOwner failed:', (err as Error).message);
    }
  }

  /**
   * Résout les player_id à notifier selon le scope de l'attachment.
   * Player → soi-même ; Gang → leader + bras_droit ; Cartel → tous admins.
   */
  private static async resolveNotifRecipients(att: SpecialistAttachment): Promise<string[]> {
    if (att.owner_type === 'player') return [att.owner_id];

    if (att.owner_type === 'gang') {
      const { GangMember } = await import('../models/GangMember');
      const repo = AppDataSource.getRepository(GangMember);
      const leadership = await repo.find({
        where: [
          { gang_id: att.owner_id, role: 'leader' as any },
          { gang_id: att.owner_id, role: 'bras_droit' as any },
        ],
        select: { player_id: true },
      });
      // Filtre humains uniquement (les NPCs n'ont pas besoin de notif)
      const { Player } = await import('../models/Player');
      const playerRepo = AppDataSource.getRepository(Player);
      const ids = leadership.map((l) => l.player_id);
      if (ids.length === 0) return [];
      const humans = await playerRepo.find({
        where: ids.map((id) => ({ id, is_npc: false as any })),
        select: { id: true },
      });
      return humans.map((p) => p.id);
    }

    if (att.owner_type === 'cartel') {
      const { CartelMember } = await import('../models/CartelMember');
      const cmRepo = AppDataSource.getRepository(CartelMember);
      const admins = await cmRepo.find({
        where: { cartel_id: att.owner_id, is_admin: true as any, status: 'active' as any },
        select: { primary_player_id: true } as any,
      });
      return admins
        .map((a: any) => a.primary_player_id)
        .filter((id: string | null) => !!id) as string[];
    }

    return [];
  }
}
