/**
 * Phase 8 (2026-04-27) — Interactions extérieures avec une prison.
 *
 * Service utilisé par les joueurs NON incarcérés qui consultent un POI prison
 * sur la carte :
 *   - getDetails(viewerId, poiId) : stats publiques + tabs « proches incarcérés
 *     ici » (gangsters de mon gang + membres autres gangs de mon cartel).
 *   - visitParloir(visitorId, prisonerId, items) : faire un parloir, transférer
 *     items (cigarettes / drogues / docs judiciaires). Risque 25% : visiteur
 *     incarcéré 1 jour direct + items saisis (destruction).
 *   - lawyerHelp(payerId, prisonerId, useOwnLawyer) : payer un avocat pour
 *     réduire la peine du prisonnier. Standard 5000 ∞ light → -20%. Avocat
 *     personnel : −5% × skill_level (skill 1→10) jusqu'à -50% pour 5★ (skill 10).
 */
import { AppDataSource } from '../config/database';
import { In } from 'typeorm';
import { Prison } from '../models/Prison';
import { POI } from '../models/POI';
import { PlayerHealth } from '../models/PlayerHealth';
import { Player } from '../models/Player';
import { GangMember } from '../models/GangMember';
import { CartelMember } from '../models/CartelMember';
import { PlayerInventory } from '../models/PlayerInventory';
import { PlayerBalances } from '../models/PlayerBalances';
import { Specialist } from '../models/Specialist';
import { SpecialistAttachment } from '../models/SpecialistAttachment';
import { Notification } from '../models/Notification';

const VISIT_FAIL_PROBABILITY = 0.25;
const VISIT_CAUGHT_PRISON_HOURS = 24;
const STANDARD_LAWYER_COST_LIGHT = 5000;
const STANDARD_LAWYER_REDUCTION = 0.20;
const PERSO_LAWYER_PER_SKILL_PCT = 0.05; // skill_level 1..10 → 5%..50%

export interface PrisonDetails {
  prison: {
    id: number;
    nom: string;
    type: string;
    ville: string;
    adresse: string;
    capacite_max: number;
    current_population: number;
    fill_pct: number;
    direction_interreg: string;
    mise_en_service: number | null;
    statut: string;
    directeur: string;
    poi_id: string | null;
  };
  close_inmates: {
    gangsters: InmateInfo[];
    cartel: InmateInfo[];
  };
}

export interface InmateInfo {
  player_id: string;
  username: string;
  character_name: string | null;
  imprisoned_until: string;
  prison_building: 'B1' | 'B2' | 'B3' | null;
}

export class PrisonInteractionService {
  /**
   * Stats prison + liste « proches incarcérés ici » (gang + cartel).
   * `prisonId` accepte soit l'id integer de la prison, soit le poi.id (uuid).
   */
  static async getDetails(viewerId: string, identifier: string | number): Promise<PrisonDetails | null> {
    let prison: Prison | null = null;
    if (typeof identifier === 'number' || /^\d+$/.test(String(identifier))) {
      prison = await AppDataSource.getRepository(Prison)
        .findOneBy({ id: Number(identifier) });
    } else {
      prison = await AppDataSource.getRepository(Prison)
        .findOneBy({ poi_id: String(identifier) });
    }
    if (!prison) return null;

    // Trouver les détenus dans cette prison
    const inmatesAll = await AppDataSource.getRepository(PlayerHealth)
      .createQueryBuilder('ph')
      .innerJoinAndSelect(Player, 'p', 'p.id = ph.player_id')
      .where('ph.prison_id = :pid', { pid: prison.id })
      .andWhere('ph.imprisoned_until IS NOT NULL')
      .andWhere('ph.imprisoned_until > NOW()')
      .getRawMany();

    // Mes coéquipiers de gang
    const myGm = await AppDataSource.getRepository(GangMember)
      .findOneBy({ player_id: viewerId });
    const myGangId = myGm?.gang_id ?? null;

    let gangPeerIds: Set<string> = new Set();
    let cartelPeerIds: Set<string> = new Set();

    if (myGangId) {
      const peers = await AppDataSource.getRepository(GangMember)
        .find({ where: { gang_id: myGangId } });
      gangPeerIds = new Set(peers.map((m) => m.player_id).filter((id) => id !== viewerId));

      // Mon cartel : via cartel_members
      const myCm = await AppDataSource.getRepository(CartelMember)
        .findOneBy({ gang_id: myGangId });
      if (myCm?.cartel_id) {
        const cartelGangs = await AppDataSource.getRepository(CartelMember)
          .find({ where: { cartel_id: myCm.cartel_id } });
        const cartelGangIds = cartelGangs.map((c) => c.gang_id).filter((g) => g !== myGangId);
        if (cartelGangIds.length > 0) {
          const cartelPeers = await AppDataSource.getRepository(GangMember)
            .find({ where: { gang_id: In(cartelGangIds) } });
          cartelPeerIds = new Set(cartelPeers.map((m) => m.player_id));
        }
      }
    }

    const toInmateInfo = (raw: any): InmateInfo => ({
      player_id: raw.ph_player_id,
      username: raw.p_username ?? '',
      character_name: raw.p_character_name ?? null,
      imprisoned_until: raw.ph_imprisoned_until,
      prison_building: raw.ph_prison_building,
    });

    const gangsters: InmateInfo[] = [];
    const cartel: InmateInfo[] = [];

    for (const raw of inmatesAll) {
      const inmate = toInmateInfo(raw);
      if (gangPeerIds.has(inmate.player_id)) gangsters.push(inmate);
      else if (cartelPeerIds.has(inmate.player_id)) cartel.push(inmate);
    }

    const fillPct = prison.capacite_max > 0
      ? Math.round((prison.current_population / prison.capacite_max) * 100)
      : 0;

    return {
      prison: {
        id: prison.id,
        nom: prison.nom,
        type: prison.type,
        ville: prison.ville,
        adresse: prison.adresse,
        capacite_max: prison.capacite_max,
        current_population: prison.current_population,
        fill_pct: fillPct,
        direction_interreg: prison.direction_interreg,
        mise_en_service: prison.mise_en_service,
        statut: prison.statut,
        directeur: `${prison.directeur_prenom} ${prison.directeur_nom}`,
        poi_id: prison.poi_id,
      },
      close_inmates: { gangsters, cartel },
    };
  }

  /**
   * Faire un parloir : transférer items au prisonnier.
   * Risque 25% (gaulé) → visiteur incarcéré 24h direct + items saisis (destruction).
   * `items` : tableau de { inventory_id, quantity } à débiter de l'inventaire visiteur.
   */
  static async visitParloir(
    visitorId: string,
    prisonerId: string,
    items: Array<{ inventory_id: string; quantity: number }>,
  ): Promise<{
    success: boolean;
    caught: boolean;
    transferred_count: number;
    visitor_imprisoned_until?: string;
    flavor: string;
  }> {
    return AppDataSource.transaction(async (tx) => {
      // Validation : visiteur libre, prisonnier incarcéré
      const vh = await tx.getRepository(PlayerHealth).findOneBy({ player_id: visitorId });
      if (vh?.imprisoned_until && new Date(vh.imprisoned_until) > new Date()) {
        throw new Error('Vous êtes incarcéré, vous ne pouvez pas faire un parloir.');
      }

      const ph = await tx.getRepository(PlayerHealth).findOneBy({ player_id: prisonerId });
      if (!ph?.imprisoned_until || new Date(ph.imprisoned_until) <= new Date()) {
        throw new Error('Cette personne n\'est plus incarcérée.');
      }

      // Validation des items à transférer (appartiennent au visiteur, quantité OK)
      const invIds = items.map((i) => i.inventory_id).filter(Boolean);
      const invRepo = tx.getRepository(PlayerInventory);
      const invItems = invIds.length > 0
        ? await invRepo.findBy({ id: In(invIds), player_id: visitorId })
        : [];
      if (invItems.length !== invIds.length) {
        throw new Error('Certains items ne vous appartiennent pas.');
      }

      // Roll 25% caught
      const caught = Math.random() < VISIT_FAIL_PROBABILITY;

      if (caught) {
        // Saisir + détruire les items du visiteur
        for (const inv of invItems) {
          const wanted = items.find((i) => i.inventory_id === inv.id)!;
          const qty = Math.max(1, Math.min(wanted.quantity, inv.quantity));
          if (qty >= inv.quantity) {
            await invRepo.delete({ id: inv.id });
          } else {
            await invRepo.update({ id: inv.id }, { quantity: inv.quantity - qty });
          }
        }

        // Incarcérer 24h le visiteur via PrisonAssignmentService (1 jour = 1 sentenceDay)
        const { PrisonAssignmentService } = await import('./prison-assignment.service');
        await PrisonAssignmentService.assignPrison(visitorId, 1);
        // PrisonAssignmentService set imprisoned_until = now + 1d
        const newPh = await tx.getRepository(PlayerHealth).findOneBy({ player_id: visitorId });

        // Notif
        try {
          await tx.getRepository(Notification).save(tx.getRepository(Notification).create({
            player_id: visitorId,
            type: 'system',
            title: 'Parloir : tu t\'es fait gauler',
            message: 'Les matons ont trouvé les items que tu tentais de faire passer. 24h de prison + items saisis.',
          }));
        } catch { /* silent */ }

        return {
          success: false,
          caught: true,
          transferred_count: 0,
          visitor_imprisoned_until: newPh?.imprisoned_until?.toISOString(),
          flavor: 'Le maton a senti le truc louche dans ton sac. T\'as merdé. 24h au mitard, items confisqués.',
        };
      }

      // Pas gaulé : transférer les items au prisonnier
      let transferred = 0;
      for (const inv of invItems) {
        const wanted = items.find((i) => i.inventory_id === inv.id)!;
        const qty = Math.max(1, Math.min(wanted.quantity, inv.quantity));

        // Decrement chez le visiteur
        if (qty >= inv.quantity) {
          await invRepo.delete({ id: inv.id });
        } else {
          await invRepo.update({ id: inv.id }, { quantity: inv.quantity - qty });
        }

        // Créer (ou incrémenter) chez le prisonnier
        const existing = await invRepo.findOne({
          where: {
            player_id: prisonerId,
            item_type: inv.item_type,
            item_subtype: inv.item_subtype,
            storage_condition: 'on_person' as any,
          },
        });
        if (existing) {
          await invRepo.update(
            { id: existing.id },
            { quantity: existing.quantity + qty },
          );
        } else {
          await invRepo.save(invRepo.create({
            player_id: prisonerId,
            item_type: inv.item_type,
            item_subtype: inv.item_subtype,
            quantity: qty,
            quality: inv.quality,
            storage_condition: 'on_person' as any,
            weight_grams: inv.weight_grams,
            uses_remaining: inv.uses_remaining,
          }));
        }
        transferred += qty;
      }

      // Notif au prisonnier
      try {
        await tx.getRepository(Notification).save(tx.getRepository(Notification).create({
          player_id: prisonerId,
          type: 'system',
          title: 'Parloir : visite reçue',
          message: `Un proche est venu te voir. ${transferred} item(s) sont passés sous le manteau.`,
        }));
      } catch { /* silent */ }

      return {
        success: true,
        caught: false,
        transferred_count: transferred,
        flavor: 'Tu glisses ton paquet sous la table. Le maton ne capte rien. Le frérot l\'embarque, sourire en coin.',
      };
    });
  }

  /**
   * Payer un avocat pour réduire la peine d'un prisonnier.
   * - useOwnLawyer=false : standard 5000 ∞ light, -20%
   * - useOwnLawyer=true : utilise un Specialist lawyer attaché au payeur,
   *   -5% × skill_level (1→10) jusqu'à -50% pour skill 10.
   */
  static async lawyerHelp(
    payerId: string,
    prisonerId: string,
    useOwnLawyer: boolean,
  ): Promise<{
    cost_light: number;
    reduction_pct: number;
    new_imprisoned_until: string | null;
  }> {
    return AppDataSource.transaction(async (tx) => {
      const ph = await tx.getRepository(PlayerHealth).findOneBy({ player_id: prisonerId });
      if (!ph?.imprisoned_until || new Date(ph.imprisoned_until) <= new Date()) {
        throw new Error('Cette personne n\'est plus incarcérée.');
      }

      let cost = STANDARD_LAWYER_COST_LIGHT;
      let reduction = STANDARD_LAWYER_REDUCTION;

      if (useOwnLawyer) {
        const att = await tx.getRepository(SpecialistAttachment)
          .createQueryBuilder('sa')
          .innerJoinAndSelect(Specialist, 's', 's.id = sa.specialist_id')
          .where('sa.owner_type = :ot', { ot: 'player' })
          .andWhere('sa.owner_id = :oid', { oid: payerId })
          .andWhere('sa.is_active = true')
          .andWhere('s.role = :role', { role: 'lawyer' })
          .orderBy('s.skill_level', 'DESC')
          .limit(1)
          .getRawOne();
        if (!att) {
          throw new Error('Vous n\'avez aucun avocat attaché. Recrutez-en un d\'abord.');
        }
        const skill = Math.max(1, Math.min(10, Number(att.s_skill_level || 1)));
        reduction = Math.min(0.50, skill * PERSO_LAWYER_PER_SKILL_PCT);
        cost = 0; // L'avocat perso est déjà payé via paySalaries — gratuit ponctuellement
      } else {
        const bal = await tx.getRepository(PlayerBalances).findOneBy({ player_id: payerId });
        if (!bal || Number(bal.infinite_light) < cost) {
          throw new Error(`Fonds insuffisants : ${cost} ∞ Light requis.`);
        }
        await tx.getRepository(PlayerBalances).decrement(
          { player_id: payerId }, 'infinite_light', cost,
        );
      }

      // Réduire imprisoned_until
      const remainingMs = new Date(ph.imprisoned_until).getTime() - Date.now();
      const reducedMs = remainingMs * (1 - reduction);
      const newEnd = new Date(Date.now() + reducedMs);
      await tx.getRepository(PlayerHealth).update(
        { player_id: prisonerId },
        { imprisoned_until: newEnd },
      );

      // Notif
      try {
        await tx.getRepository(Notification).save(tx.getRepository(Notification).create({
          player_id: prisonerId,
          type: 'system',
          title: 'Avocat payé : peine réduite',
          message: `Un proche t'a payé un avocat. Peine réduite de ${Math.round(reduction * 100)}%.`,
        }));
      } catch { /* silent */ }

      return {
        cost_light: cost,
        reduction_pct: Math.round(reduction * 100),
        new_imprisoned_until: newEnd.toISOString(),
      };
    });
  }
}
