import { AppDataSource } from '../config/database';
import { Business } from '../models/Business';
import { ForceRaid } from '../models/ForceRaid';
import { Player } from '../models/Player';
import { ForceBribeService } from './force-bribe.service';

/**
 * FBI + DEA (Phase 9, 2026-04-20).
 *
 * Forces fédérales basées US, scope mondial. Raids automatisés contre les cartels
 * ou joueurs dont la chaleur dépasse des seuils soutenus :
 *   - FBI : cartel.heat ≥ 95 (ou player.chaleur ≥ 95 soutenue 7j) → shutdown
 *     permanent d'un business illégal. Max 1 raid/semaine/cartel.
 *   - DEA : cartel.heat ≥ 90 + présence drogue (drug_lab/point_de_deal) → raid
 *     spécialisé. Max 1/semaine/cartel.
 *
 * Les bribes actifs (ForceBribeService.isBribedActive) désactivent le raid pour
 * la durée du bribe.
 *
 * NOTE: on ne modélise pas physiquement les "agents FBI/DEA" sur la carte ici
 * (simplicité). Les raids sont des events backend CRON qui apparaissent comme
 * notifications + business.is_permanent_shutdown=true.
 */

const businessRepo = () => AppDataSource.getRepository(Business);
const raidRepo = () => AppDataSource.getRepository(ForceRaid);
const playerRepo = () => AppDataSource.getRepository(Player);

export class FederalAgencyService {
  static readonly FBI_HEAT_THRESHOLD = 95;
  static readonly DEA_HEAT_THRESHOLD = 90;
  static readonly RAID_WEEKLY_CAP = 1;

  /**
   * CRON quotidien : évalue les cibles potentielles FBI.
   * Si cartel heat ≥ 95 + pas de raid FBI depuis 7 jours + pas de bribe FBI actif
   * sur au moins 1 membre → sélectionne business illegal_activity_type du cartel
   * et applique shutdown permanent.
   *
   * MVP : pas de table cartel en prod actuellement — on opère au niveau player
   * (chaleur individuelle ≥ 95 soutenue 3 jours).
   */
  static async processFBIRaids(): Promise<{ raids: number }> {
    const oneWeekAgo = new Date(Date.now() - 7 * 24 * 3600 * 1000);
    let raids = 0;

    // Cible niveau joueur : chaleur ≥ 95 ET au moins 1 business illegal actif
    // (proxy pour "cartel heat" en l'absence de table cartel)
    const candidates = await playerRepo()
      .createQueryBuilder('p')
      .innerJoin('player_gauges', 'g', 'g.player_id = p.id')
      .where('g.chaleur >= :t', { t: FederalAgencyService.FBI_HEAT_THRESHOLD })
      .getMany();

    for (const player of candidates) {
      // Skip si bribe FBI actif
      if (await ForceBribeService.isBribedActive(player.id, 'fbi')) continue;

      // Skip si raid FBI dans les 7 derniers jours sur ce joueur
      const recentRaid = await raidRepo()
        .createQueryBuilder('r')
        .where('r.force = :f', { f: 'fbi' })
        .andWhere('r.target_player_id = :p', { p: player.id })
        .andWhere('r.occurred_at >= :d', { d: oneWeekAgo })
        .getOne();
      if (recentRaid) continue;

      // Sélectionne 1 business illegal actif du joueur
      const target = await businessRepo()
        .createQueryBuilder('b')
        .where('b.player_id = :p', { p: player.id })
        .andWhere('b.illegal_activity_type IS NOT NULL')
        .andWhere('b.is_permanent_shutdown = false')
        .orderBy('b.illegal_activity_revenue_per_day', 'DESC')
        .getOne();
      if (!target) continue;

      target.is_permanent_shutdown = true;
      target.permanent_shutdown_reason = 'fbi_raid';
      target.permanent_shutdown_at = new Date();
      target.illegal_activity_type = null;
      target.illegal_activity_revenue_per_day = 0;
      target.illegal_heat_generated = 0;
      target.closed_until = new Date(Date.now() + 30 * 24 * 3600 * 1000);
      await businessRepo().save(target);

      await raidRepo().save(raidRepo().create({
        force: 'fbi',
        target_player_id: player.id,
        target_business_id: target.id,
        shutdown_permanent: true,
        reason: 'heat ≥ 95 sustained (FBI raid)',
      }));

      raids++;
    }

    return { raids };
  }

  /**
   * CRON quotidien DEA : ciblé trafic drogue.
   * Priorise drug_lab warehouses + illegal_activity_type='point_de_deal'.
   */
  static async processDEARaids(): Promise<{ raids: number }> {
    const oneWeekAgo = new Date(Date.now() - 7 * 24 * 3600 * 1000);
    let raids = 0;

    const candidates = await playerRepo()
      .createQueryBuilder('p')
      .innerJoin('player_gauges', 'g', 'g.player_id = p.id')
      .where('g.chaleur >= :t', { t: FederalAgencyService.DEA_HEAT_THRESHOLD })
      .getMany();

    for (const player of candidates) {
      if (await ForceBribeService.isBribedActive(player.id, 'dea')) continue;

      const recentRaid = await raidRepo()
        .createQueryBuilder('r')
        .where('r.force = :f', { f: 'dea' })
        .andWhere('r.target_player_id = :p', { p: player.id })
        .andWhere('r.occurred_at >= :d', { d: oneWeekAgo })
        .getOne();
      if (recentRaid) continue;

      // Cible : business avec illegal_activity_type='point_de_deal' (prioritaire DEA)
      const target = await businessRepo()
        .createQueryBuilder('b')
        .where('b.player_id = :p', { p: player.id })
        .andWhere('b.illegal_activity_type = :act', { act: 'point_de_deal' })
        .andWhere('b.is_permanent_shutdown = false')
        .getOne();
      if (!target) continue;

      target.is_permanent_shutdown = true;
      target.permanent_shutdown_reason = 'dea_raid';
      target.permanent_shutdown_at = new Date();
      target.illegal_activity_type = null;
      target.illegal_activity_revenue_per_day = 0;
      target.illegal_heat_generated = 0;
      target.closed_until = new Date(Date.now() + 30 * 24 * 3600 * 1000);
      await businessRepo().save(target);

      await raidRepo().save(raidRepo().create({
        force: 'dea',
        target_player_id: player.id,
        target_business_id: target.id,
        shutdown_permanent: true,
        reason: 'heat ≥ 90 + drogue (DEA raid)',
      }));
      raids++;
    }

    return { raids };
  }
}
