/**
 * Phase 4 (2026-04-26) — Soudoyer POI gouvernemental.
 *
 * Le joueur paie un POI police/mairie/tribunal pour réduire sa chaleur ou
 * obtenir des items judiciaires (Alibi, Jurisprudence). Modèle distinct de
 * ForceBribeService (qui gère l'immunité forfaitaire des forces).
 *
 * Trois flux :
 *   - police/townhall récurrent : prélèvement quotidien tant qu'actif. Si
 *     fonds insuffisants au cycle suivant → cancel auto status='insufficient_funds'.
 *   - police/townhall one_shot : 1 paiement = 1 effet immédiat, status='completed'.
 *   - courthouse : toujours one_shot avec grants items + bonus tier 3 (libère gang).
 *
 * Cap : 1×/joueur/POI/jour (vérifié au moment du bribe), enforced via une
 * subquery dans bribe() qui rejette si un row 'active' ou 'completed' existe
 * pour le même couple (player_id, poi_id) avec last_paid_at >= début de la journée.
 */
import { AppDataSource } from '../config/database';
import { In } from 'typeorm';
import { PoiBribe } from '../models/PoiBribe';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerInventory } from '../models/PlayerInventory';
import { PlayerHealth } from '../models/PlayerHealth';
import { GangMember } from '../models/GangMember';
import { POI } from '../models/POI';
import { Notification } from '../models/Notification';
import {
  POI_BRIBE_TIERS, findBribeTier, poiKindFromIcon,
  type PoiBribeTier,
} from '../constants/poi-bribes';
import type { PoiBribeKind } from '../models/PoiBribe';
import { TransactionService } from './transaction.service';
import { HeatService } from './heat.service';
import { NotificationService } from './notification.service';

const bribeRepo = () => AppDataSource.getRepository(PoiBribe);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const invRepo = () => AppDataSource.getRepository(PlayerInventory);
const healthRepo = () => AppDataSource.getRepository(PlayerHealth);
const gmRepo = () => AppDataSource.getRepository(GangMember);
const poiRepo = () => AppDataSource.getRepository(POI);

const DEFAULT_USES_BY_ITEM: Record<string, number> = {
  Alibi: 1,
  Jurisprudence: 2,
  // Phase 5b items magic exit (granted via missions narratives, pas via bribes)
  'Grâce présidentielle': 1,
  'Vice de procédure': 1,
  'Appel accordé': 1,
};

export interface BribeContext {
  poi_id: string;
  poi_kind: PoiBribeKind;
  tier: number;
  is_recurring: boolean;
}

export interface BribeResult {
  bribe_id: string;
  amount_paid: number;
  heat_applied: number;
  granted_items: Array<{ item_subtype: string; quantity: number }>;
  released_gang_members: string[];
  is_recurring: boolean;
  next_payment_at: string | null;
}

export class PoiBribeService {
  /**
   * Décrit les options disponibles pour un POI donné.
   * Utilisé par le frontend pour générer la liste déroulante crescendo.
   */
  static async describeOptions(poiId: string): Promise<{
    poi_kind: PoiBribeKind;
    tiers: PoiBribeTier[];
  } | null> {
    const poi = await poiRepo().findOne({ where: { id: poiId } });
    if (!poi) return null;
    const kind = poiKindFromIcon(poi.icon);
    if (!kind) return null;
    return { poi_kind: kind, tiers: POI_BRIBE_TIERS[kind] };
  }

  /**
   * Effectue le paiement et applique les effets.
   *
   * Cap : 1×/joueur/POI/jour vérifié avant le débit.
   */
  static async bribe(playerId: string, ctx: BribeContext): Promise<BribeResult> {
    const poi = await poiRepo().findOne({ where: { id: ctx.poi_id } });
    if (!poi) throw new Error('POI introuvable');
    const kind = poiKindFromIcon(poi.icon);
    if (!kind) throw new Error('Ce POI n\'accepte pas le soudoiement');
    if (kind !== ctx.poi_kind) throw new Error(`POI mismatch: ${kind} attendu, ${ctx.poi_kind} reçu`);

    const tierDef = findBribeTier(kind, ctx.tier);
    if (!tierDef) throw new Error(`Tier ${ctx.tier} non disponible pour ${kind}`);

    // Cap 1×/POI/joueur/jour
    const dayStart = new Date(); dayStart.setHours(0, 0, 0, 0);
    const recent = await bribeRepo()
      .createQueryBuilder('b')
      .where('b.player_id = :pid', { pid: playerId })
      .andWhere('b.poi_id = :poiId', { poiId: ctx.poi_id })
      .andWhere('b.last_paid_at >= :ds', { ds: dayStart })
      .andWhere('b.status IN (:...st)', { st: ['active', 'completed'] })
      .getCount();
    if (recent > 0) {
      throw new Error('Vous avez déjà soudoyé ce POI aujourd\'hui (1× par jour max)');
    }

    // Tribunal : toujours one_shot (forcé). Pour police/townhall : si is_recurring
    // demandé mais cycle_kind='one_shot' impossible côté barème, on respecte.
    const isOneShot = tierDef.cycle_kind === 'one_shot';
    const isRecurring = !isOneShot && ctx.is_recurring;

    // Vérification fonds
    const bal = await balancesRepo().findOne({ where: { player_id: playerId } });
    const balField = tierDef.currency;
    const balVal = Number((bal as any)?.[balField] ?? 0);
    if (!bal || balVal < tierDef.amount) {
      throw new Error(`Fonds insuffisants : ${tierDef.amount} ${tierDef.currency} requis, ${balVal} disponibles`);
    }

    // Effets dans une transaction
    return AppDataSource.transaction(async (tx) => {
      const txBalRepo = tx.getRepository(PlayerBalances);
      const txBribeRepo = tx.getRepository(PoiBribe);

      // 1. Débit
      await txBalRepo.decrement({ player_id: playerId }, balField, tierDef.amount);

      // 2. Heat application via HeatService (source unique pour HeatEvent trail)
      await HeatService.applyToPlayer(
        playerId, tierDef.heat_delta, `bribe_${kind}_t${ctx.tier}`, 'poi-bribe',
      );

      // 3. Items granted (Alibi, Jurisprudence) — uses_remaining via DEFAULT_USES_BY_ITEM
      const grantedItems: Array<{ item_subtype: string; quantity: number }> = [];
      if (tierDef.grants_items) {
        for (const grant of tierDef.grants_items) {
          const txInvRepo = tx.getRepository(PlayerInventory);
          const existing = await txInvRepo.findOne({
            where: {
              player_id: playerId,
              item_type: 'document',
              item_subtype: grant.item_subtype,
            },
          });
          const usesPerUnit = DEFAULT_USES_BY_ITEM[grant.item_subtype] ?? 1;
          const addUses = grant.quantity * usesPerUnit;
          if (existing) {
            await txInvRepo.update(
              { id: existing.id },
              {
                quantity: existing.quantity + grant.quantity,
                uses_remaining: (existing.uses_remaining ?? 0) + addUses,
              },
            );
          } else {
            await txInvRepo.save(txInvRepo.create({
              player_id: playerId,
              item_type: 'document',
              item_subtype: grant.item_subtype,
              quantity: grant.quantity,
              quality: 5,
              storage_condition: 'on_person',
              weight_grams: 0,
              uses_remaining: addUses,
            } as any));
          }
          grantedItems.push({ item_subtype: grant.item_subtype, quantity: grant.quantity });
        }
      }

      // 4. Bonus tier 3 tribunal : libère tous les gangsters du gang direct
      const releasedGangMembers: string[] = [];
      if (tierDef.releases_gang_members) {
        const txHealthRepo = tx.getRepository(PlayerHealth);
        const txGmRepo = tx.getRepository(GangMember);

        const playerGm = await txGmRepo.findOne({ where: { player_id: playerId } });
        if (playerGm?.gang_id) {
          const gangPeers = await txGmRepo.find({ where: { gang_id: playerGm.gang_id } });
          const peerIds = gangPeers.map(g => g.player_id).filter(id => id !== playerId);
          if (peerIds.length > 0) {
            const incarcerated = await txHealthRepo.find({
              where: { player_id: In(peerIds) },
            });
            const now = new Date();
            for (const ph of incarcerated) {
              if (ph.imprisoned_until && new Date(ph.imprisoned_until) > now) {
                await txHealthRepo.update(
                  { player_id: ph.player_id },
                  { imprisoned_until: null },
                );
                releasedGangMembers.push(ph.player_id);
              }
            }
          }
        }
      }

      // 5. Crée le row PoiBribe
      const nextPaymentAt = isRecurring
        ? new Date(Date.now() + cycleDurationMs(tierDef.cycle_kind))
        : new Date(Date.now() + 86400000); // sentinelle pour les one_shot, jamais lu
      const status = isOneShot ? 'completed' : 'active';

      const saved = await txBribeRepo.save(txBribeRepo.create({
        player_id: playerId,
        poi_id: ctx.poi_id,
        poi_kind: kind,
        tier: ctx.tier,
        amount_per_cycle: tierDef.amount,
        currency: tierDef.currency,
        heat_delta_per_cycle: tierDef.heat_delta,
        cycle_kind: tierDef.cycle_kind,
        is_recurring: isRecurring,
        status,
        next_payment_at: nextPaymentAt,
        last_paid_at: new Date(),
        granted_items: grantedItems,
        released_gang_members: releasedGangMembers,
      } as any)) as unknown as PoiBribe;

      // 6. Log transaction comptable (categorie crime)
      await TransactionService.log({
        player_id: playerId,
        category: 'crime',
        type: 'out',
        amount: tierDef.amount,
        currency: tierDef.currency,
        description: `Soudoyer ${kind} tier ${ctx.tier}${isRecurring ? ' (récurrent)' : ''}`,
      });

      // 7. Notification flavor + récap effet
      await tx.getRepository(Notification).save(tx.getRepository(Notification).create({
        player_id: playerId,
        type: 'system',
        title: kind === 'courthouse'
          ? 'Affaire classée'
          : kind === 'townhall'
          ? 'Sous main accepté'
          : 'Bakchich accepté',
        message: bribeNotificationMessage(kind, tierDef, grantedItems, releasedGangMembers, isRecurring),
      }));

      return {
        bribe_id: saved.id,
        amount_paid: tierDef.amount,
        heat_applied: tierDef.heat_delta,
        granted_items: grantedItems,
        released_gang_members: releasedGangMembers,
        is_recurring: isRecurring,
        next_payment_at: isRecurring ? nextPaymentAt.toISOString() : null,
      };
    });
  }

  /** Annule un bribe récurrent (ne fait rien si déjà inactif). */
  static async cancel(playerId: string, bribeId: string): Promise<void> {
    const row = await bribeRepo().findOne({ where: { id: bribeId, player_id: playerId } });
    if (!row) throw new Error('Bribe introuvable');
    if (row.status !== 'active') return;
    await bribeRepo().update(
      { id: row.id },
      { status: 'cancelled', cancel_reason: 'user', cancelled_at: new Date() },
    );
  }

  /** Liste les bribes actifs/historique d'un joueur (UI panneau « Mes arrangements »). */
  static async listForPlayer(playerId: string): Promise<PoiBribe[]> {
    return bribeRepo().find({
      where: { player_id: playerId },
      order: { created_at: 'DESC' },
      take: 50,
    });
  }

  /**
   * CRON — process all due recurring bribes. Appelé toutes les 5 minutes.
   * Pour chaque bribe actif récurrent dont next_payment_at <= now :
   *   - Si fonds suffisants : débit + heat + grants + reschedule next
   *   - Sinon : cancel auto status='insufficient_funds' + notif
   */
  static async processDue(): Promise<{ processed: number; cancelled_insuf: number }> {
    const now = new Date();
    const due = await bribeRepo()
      .createQueryBuilder('b')
      .where('b.status = :s', { s: 'active' })
      .andWhere('b.is_recurring = true')
      .andWhere('b.next_payment_at <= :now', { now })
      .getMany();

    let processed = 0;
    let cancelledInsuf = 0;

    for (const b of due) {
      const tierDef = findBribeTier(b.poi_kind, b.tier);
      if (!tierDef) continue;

      const bal = await balancesRepo().findOne({ where: { player_id: b.player_id } });
      const balVal = Number((bal as any)?.[b.currency] ?? 0);

      if (!bal || balVal < b.amount_per_cycle) {
        await bribeRepo().update(
          { id: b.id },
          {
            status: 'insufficient_funds',
            cancel_reason: 'insufficient_funds',
            cancelled_at: now,
          },
        );
        cancelledInsuf++;
        try {
          await NotificationService.create({
            player_id: b.player_id,
            type: 'system',
            title: 'Arrangement annulé',
            message: `Fonds insuffisants pour le paiement de votre arrangement avec ${b.poi_kind} (${b.amount_per_cycle} ${b.currency}). L'arrangement est annulé.`,
            link: null,
          });
        } catch { /* silent */ }
        continue;
      }

      // Débit + heat
      await balancesRepo().decrement({ player_id: b.player_id }, b.currency, b.amount_per_cycle);
      await HeatService.applyToPlayer(
        b.player_id,
        Number(b.heat_delta_per_cycle),
        `bribe_recur_${b.poi_kind}_t${b.tier}`,
        'poi-bribe-cron',
      );
      await TransactionService.log({
        player_id: b.player_id,
        category: 'crime', type: 'out',
        amount: b.amount_per_cycle, currency: b.currency,
        description: `Soudoyer ${b.poi_kind} tier ${b.tier} (récurrent)`,
      });

      // Reschedule
      await bribeRepo().update(
        { id: b.id },
        {
          last_paid_at: now,
          next_payment_at: new Date(now.getTime() + cycleDurationMs(b.cycle_kind)),
        },
      );
      processed++;
    }

    return { processed, cancelled_insuf: cancelledInsuf };
  }
}

function cycleDurationMs(cycleKind: 'daily' | 'monthly' | 'one_shot'): number {
  if (cycleKind === 'daily') return 86400000;        // 24h
  if (cycleKind === 'monthly') return 30 * 86400000;  // 30j
  return Number.MAX_SAFE_INTEGER; // one_shot ne devrait pas être planifié
}

function bribeNotificationMessage(
  kind: PoiBribeKind,
  tier: PoiBribeTier,
  grants: Array<{ item_subtype: string; quantity: number }>,
  released: string[],
  isRecurring: boolean,
): string {
  const parts: string[] = [];
  if (tier.heat_delta < 0) {
    parts.push(`−${Math.abs(tier.heat_delta)} chaleur`);
  }
  if (grants.length > 0) {
    parts.push(grants.map(g => `${g.quantity}× ${g.item_subtype}`).join(', '));
  }
  if (released.length > 0) {
    parts.push(`${released.length} gangster(s) libéré(s)`);
  }
  const recur = isRecurring ? ` Arrangement récurrent en cours.` : '';
  return `Paiement accepté : ${parts.join(' · ')}.${recur}`;
}
