import { AppDataSource } from '../config/database';
import { MoreThan } from 'typeorm';
import { ForceBribe } from '../models/ForceBribe';
import { PlayerBalances } from '../models/PlayerBalances';
import {
  ForceKind, BRIBE_COSTS, BRIBE_WEEKLY_CAP_DAYS, BRIBE_ESCALATOR_RATIO,
  BRIBE_ESCALATOR_RESET_HOURS, BRIBE_DISCOVERY_CHANCE,
  BRIBE_CORRUPTION_RECORD_POINTS, BRIBE_DEA_HOSTILE_BACKLASH_DAYS,
  BRIBE_DEFAULT_DURATION_DAYS,
} from '../constants/force-bribes';
import { TransactionService } from './transaction.service';
import { GameSettingsService } from './game-settings.service';

/**
 * Phase 16 (2026-04-22) — tarifs/plafonds/discovery editables via GameSettings.
 * Clés : `bribe.cost.<force>`, `bribe.weekly_cap.<force>`, `bribe.discovery_chance`,
 * `bribe.escalator_ratio`. Fallback = constants statiques si pas d'override admin.
 */
async function resolveBribeCost(force: ForceKind): Promise<number> {
  return GameSettingsService.get(`bribe.cost.${force}`, BRIBE_COSTS[force]);
}
async function resolveWeeklyCap(force: ForceKind): Promise<number> {
  return GameSettingsService.get(`bribe.weekly_cap.${force}`, BRIBE_WEEKLY_CAP_DAYS[force]);
}
async function resolveDiscoveryChance(): Promise<number> {
  return GameSettingsService.get('bribe.discovery_chance', BRIBE_DISCOVERY_CHANCE);
}
async function resolveEscalatorRatio(): Promise<number> {
  return GameSettingsService.get('bribe.escalator_ratio', BRIBE_ESCALATOR_RATIO);
}

const bribeRepo = () => AppDataSource.getRepository(ForceBribe);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);

/**
 * Pots-de-vin aux forces Police/GIGN/FBI/DEA (Phase 9, 2026-04-20).
 *
 * Plafonds, escalator, discovery pour éviter l'immunité infinie.
 * Les bribes sont INDÉPENDANTS par force (bribe Police n'affecte pas GIGN).
 */
export class ForceBribeService {
  /**
   * Teste si un joueur a un bribe actif pour une force donnée (expires_at > now).
   * Appelé par PolicePatrolService.updatePatrolActivity et FbiAgencyService/DeaAgencyService.
   */
  static async isBribedActive(playerId: string, force: ForceKind): Promise<boolean> {
    const count = await bribeRepo().count({
      where: { payer_player_id: playerId, force, expires_at: MoreThan(new Date()) },
    });
    return count > 0;
  }

  /**
   * Crée un pot-de-vin. Applique les garde-fous (cap hebdo, escalator, discovery).
   */
  static async bribe(
    playerId: string,
    force: ForceKind,
    days: number = BRIBE_DEFAULT_DURATION_DAYS,
  ): Promise<{
    amount: number;
    expires_at: string;
    discovered: boolean;
    weekly_used_days: number;
    weekly_cap_days: number;
  }> {
    const d = Math.floor(Number(days) || 1);
    if (d < 1) throw new Error('days doit être ≥ 1');

    // 1. Check cap hebdo : somme jours bribes actifs/récents <= cap
    const oneWeekAgo = new Date(Date.now() - 7 * 24 * 3600 * 1000);
    const recentBribes = await bribeRepo()
      .createQueryBuilder('b')
      .where('b.payer_player_id = :pid', { pid: playerId })
      .andWhere('b.force = :f', { f: force })
      .andWhere('b.paid_at >= :w', { w: oneWeekAgo })
      .getMany();
    const usedDays = recentBribes.reduce((sum, b) => {
      const dur = Math.ceil((b.expires_at.getTime() - b.paid_at.getTime()) / (24 * 3600 * 1000));
      return sum + dur;
    }, 0);
    const cap = await resolveWeeklyCap(force);
    if (usedDays + d > cap) {
      throw new Error(`Plafond hebdomadaire atteint : ${cap - usedDays} jour(s) restants cette semaine sur ${force.toUpperCase()}`);
    }

    // 2. Escalator : ×ratio si bribe <48h depuis le précédent même force
    const lastBribe = recentBribes
      .sort((a, b) => b.paid_at.getTime() - a.paid_at.getTime())[0];
    const unitCost = await resolveBribeCost(force);
    const escalatorRatio = await resolveEscalatorRatio();
    const baseCost = unitCost * d;
    let effectiveCost = baseCost;
    if (lastBribe) {
      const sinceH = (Date.now() - lastBribe.paid_at.getTime()) / 3600000;
      if (sinceH < 48) effectiveCost = Math.round(baseCost * escalatorRatio);
    }

    // 3. Check balance
    const bal = await balancesRepo().findOneBy({ player_id: playerId });
    if (!bal || Number(bal.infinite_shadow) < effectiveCost) {
      throw new Error(`Fonds shadow insuffisants (${effectiveCost} ∞ requis)`);
    }

    // 4. Discovery (15% par défaut, editable via GameSettings)
    const discoveryChance = await resolveDiscoveryChance();
    const discovered = Math.random() < discoveryChance;

    // 5. Atomic
    const expiresAt = new Date(Date.now() + d * 24 * 3600 * 1000);

    return AppDataSource.transaction(async tx => {
      await tx.getRepository(PlayerBalances).decrement({ player_id: playerId }, 'infinite_shadow', effectiveCost);

      await tx.getRepository(ForceBribe).save(
        tx.getRepository(ForceBribe).create({
          payer_player_id: playerId,
          force,
          amount: effectiveCost,
          paid_at: new Date(),
          expires_at: expiresAt,
          discovered,
        }),
      );

      await TransactionService.log({
        player_id: playerId, category: 'crime', type: 'out',
        amount: effectiveCost, currency: 'infinite_shadow',
        description: `Pot-de-vin ${force.toUpperCase()} ${d}j`,
      });

      // Backlash discovery
      if (discovered) {
        try {
          const { JudicialService } = await import('./judicial.service');
          await JudicialService.registerCrimeAndMaybeConvict(playerId, {
            crime_type: 'corruption' as any,
            description: `Bribe ${force.toUpperCase()} découvert`,
            is_violent: false,
            arrest_probability: 0.3,
            police_risk: BRIBE_CORRUPTION_RECORD_POINTS,
          });
        } catch { /* silent */ }

        // Domino FBI découvert → DEA hostile 7j (bribe négatif virtuel)
        // On ne peut pas créer un bribe négatif, mais on log l'info pour FBI/DEA services
        if (force === 'fbi') {
          try {
            const { HeatEventService } = await import('./heat-event.service');
            await HeatEventService.log({
              target_type: 'player', target_id: playerId,
              delta: 0, new_value: 0,
              reason: 'fbi_bribe_discovered_dea_hostile_7d',
              source: 'force-bribe',
              metadata: { expires_at: new Date(Date.now() + BRIBE_DEA_HOSTILE_BACKLASH_DAYS * 24 * 3600 * 1000).toISOString() },
            });
          } catch { /* silent */ }
        }
      }

      return {
        amount: effectiveCost,
        expires_at: expiresAt.toISOString(),
        discovered,
        weekly_used_days: usedDays + d,
        weekly_cap_days: cap,
      };
    });
  }

  /** Status global des 4 forces pour un joueur (UI panneau pot-de-vin). */
  static async getStatusForPlayer(playerId: string): Promise<Record<ForceKind, {
    is_active: boolean;
    expires_at: string | null;
    weekly_used_days: number;
    weekly_cap_days: number;
    next_cost: number;
  }>> {
    const now = new Date();
    const oneWeekAgo = new Date(Date.now() - 7 * 24 * 3600 * 1000);
    const all = await bribeRepo()
      .createQueryBuilder('b')
      .where('b.payer_player_id = :pid', { pid: playerId })
      .andWhere('b.paid_at >= :w', { w: oneWeekAgo })
      .getMany();

    const forces: ForceKind[] = ['police', 'gign', 'fbi', 'dea'];
    const result = {} as Record<ForceKind, any>;
    const escalatorRatio = await resolveEscalatorRatio();

    for (const f of forces) {
      const bribes = all.filter(b => b.force === f);
      const active = bribes.find(b => b.expires_at > now);
      const usedDays = bribes.reduce((s, b) => s + Math.ceil((b.expires_at.getTime() - b.paid_at.getTime()) / (24 * 3600 * 1000)), 0);
      const last = bribes.sort((a, b) => b.paid_at.getTime() - a.paid_at.getTime())[0];
      const sinceH = last ? (now.getTime() - last.paid_at.getTime()) / 3600000 : Infinity;
      const unitCost = await resolveBribeCost(f);
      const nextCost = sinceH < 48 ? Math.round(unitCost * escalatorRatio) : unitCost;

      result[f] = {
        is_active: !!active,
        expires_at: active ? active.expires_at.toISOString() : null,
        weekly_used_days: usedDays,
        weekly_cap_days: await resolveWeeklyCap(f),
        next_cost: nextCost,
      };
    }
    return result;
  }
}
