import { AppDataSource } from '../config/database';
import { Residence } from '../models/Residence';
import { Player } from '../models/Player';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerInventory } from '../models/PlayerInventory';
import { getDealingRate, DEALING_RATES } from '../constants/dealing-rates';
import { DRUGS } from '../constants/drugs';
import { TransactionService } from './transaction.service';
import { HeatService } from './heat.service';
import { NotificationService } from './notification.service';

/**
 * audit 15-04-2026 Phase 13.b — Point de deal FIXE en residence.
 *
 * Prerequis : la residence doit etre possedee par le joueur ET is_planque_active=true.
 * Le point de deal genere du revenu horaire (CRON) mais aussi de la chaleur locale.
 * Si la chaleur locale depasse un seuil, un raid police peut se declencher.
 *
 * Cycle de vie :
 *   1. activateSpot(playerId, residenceId, drugName)
 *   2. CRON horaire : tickHourlyRevenue()
 *   3. CRON horaire : processRaidRisk()
 *   4. deactivateSpot(playerId, residenceId) OU raid police force la desactivation
 */

const residenceRepo = () => AppDataSource.getRepository(Residence);
const playerRepo = () => AppDataSource.getRepository(Player);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const inventoryRepo = () => AppDataSource.getRepository(PlayerInventory);

/** Seuil de chaleur locale au-dessus duquel un raid est possible */
const RAID_HEAT_THRESHOLD = 70;
/** Cooldown entre 2 raids sur le meme spot (24h en ms) */
const RAID_COOLDOWN_MS = 24 * 60 * 60 * 1000;
/** Chaleur locale ajoutee par tick horaire (base, * heat_multiplier du dealing rate) */
const BASE_HEAT_PER_TICK = 5;
/** Probabilite de raid par tick quand heat >= seuil (0..1) */
const RAID_CHANCE_BASE = 0.15;
/** Nombre de gangsters fictifs actifs au spot fixe (1 gangster fixe = le "dealer maison") */
const FIXED_SPOT_GANGSTER_EQUIV = 1;

export class PointDeDealService {

  /**
   * Active un point de deal fixe dans une residence du joueur.
   * Conditions :
   *   - residence owned by playerId + is_planque_active=true
   *   - drug_name valide dans DEALING_RATES
   *   - pas deja actif
   */
  static async activateSpot(
    playerId: string,
    residenceId: string,
    drugName: string,
  ): Promise<{ success: boolean; message: string }> {
    const res = await residenceRepo().findOne({ where: { id: residenceId } });
    if (!res) return { success: false, message: 'Residence introuvable' };
    if (res.player_id !== playerId) return { success: false, message: 'Ce n\'est pas votre residence' };
    if (!res.is_planque_active) return { success: false, message: 'La planque doit etre active pour installer un point de deal' };
    if (res.deal_spot_active) return { success: false, message: 'Un point de deal est deja actif ici' };

    const rate = getDealingRate(drugName);
    if (!rate) return { success: false, message: `Drogue "${drugName}" inconnue ou indisponible` };

    // Verify player has at least some stock of this drug
    const drugDef = DRUGS.find(d => d.name.toLowerCase() === drugName.toLowerCase());
    if (!drugDef) return { success: false, message: `Definition de drogue introuvable pour "${drugName}"` };

    const stock = await inventoryRepo().findOne({
      where: {
        player_id: playerId,
        item_type: 'drug',
        item_subtype: drugName,
      },
    });
    if (!stock || stock.quantity <= 0) {
      return { success: false, message: `Vous n'avez pas de ${drugName} en stock` };
    }

    await residenceRepo().update(residenceId, {
      deal_spot_active: true,
      deal_spot_drug: drugName,
      deal_spot_heat: 0,
      deal_spot_activated_at: new Date(),
      deal_spot_last_tick_at: new Date(),
      deal_spot_last_raid_at: null,
    });

    return { success: true, message: `Point de deal ${drugName} active dans ${res.name}` };
  }

  /**
   * Desactive un point de deal fixe.
   */
  static async deactivateSpot(
    playerId: string,
    residenceId: string,
  ): Promise<{ success: boolean; message: string }> {
    const res = await residenceRepo().findOne({ where: { id: residenceId } });
    if (!res) return { success: false, message: 'Residence introuvable' };
    if (res.player_id !== playerId) return { success: false, message: 'Ce n\'est pas votre residence' };
    if (!res.deal_spot_active) return { success: false, message: 'Aucun point de deal actif ici' };

    await residenceRepo().update(residenceId, {
      deal_spot_active: false,
      deal_spot_drug: null,
      deal_spot_heat: 0,
      deal_spot_activated_at: null,
    });

    return { success: true, message: 'Point de deal desactive' };
  }

  /**
   * CRON horaire : genere les revenus de TOUS les deal spots actifs.
   *
   * Pour chaque spot :
   *   1. Calcule les unites vendues = quota * FIXED_SPOT_GANGSTER_EQUIV (1)
   *   2. Verifie que le stock du joueur est suffisant (sinon vend le reste)
   *   3. Decremente l'inventaire du joueur
   *   4. Credite revenue en ∞_shadow
   *   5. Incremente deal_spot_heat
   */
  static async tickHourlyRevenue(): Promise<{ processed: number; totalRevenue: number }> {
    const activeSpots = await residenceRepo().find({
      where: { deal_spot_active: true },
    });

    let processed = 0;
    let totalRevenue = 0;

    for (const spot of activeSpots) {
      if (!spot.deal_spot_drug) continue;

      const rate = getDealingRate(spot.deal_spot_drug);
      if (!rate) continue;

      const drugDef = DRUGS.find(d => d.name.toLowerCase() === spot.deal_spot_drug!.toLowerCase());
      if (!drugDef) continue;

      // Units sellable this tick
      const maxUnits = rate.quota_per_gangster_per_hour * FIXED_SPOT_GANGSTER_EQUIV;

      // Check stock
      const stock = await inventoryRepo().findOne({
        where: {
          player_id: spot.player_id,
          item_type: 'drug',
          item_subtype: spot.deal_spot_drug,
        },
      });
      if (!stock || stock.quantity <= 0) {
        // Auto-deactivate if out of stock
        await residenceRepo().update(spot.id, {
          deal_spot_active: false,
          deal_spot_drug: null,
          deal_spot_heat: 0,
        });
        continue;
      }

      const actualSold = Math.min(maxUnits, stock.quantity);
      const revenue = actualSold * drugDef.retail_price;

      // Decrement inventory
      stock.quantity -= actualSold;
      if (stock.quantity <= 0) {
        await inventoryRepo().remove(stock);
      } else {
        await inventoryRepo().save(stock);
      }

      // Credit player ∞_shadow
      const balances = await balancesRepo().findOne({ where: { player_id: spot.player_id } });
      if (balances) {
        balances.infinite_shadow += revenue;
        await balancesRepo().save(balances);
      }

      // Log transaction
      await TransactionService.log({
        player_id: spot.player_id,
        category: 'crime',
        type: 'in',
        amount: revenue,
        currency: 'infinite_shadow',
        description: `Point de deal ${spot.deal_spot_drug}: ${actualSold} ${rate.unit} vendus`,
      });

      // Increment local heat
      const heatDelta = Math.ceil(BASE_HEAT_PER_TICK * rate.heat_multiplier);
      const newHeat = Math.min(100, (spot.deal_spot_heat ?? 0) + heatDelta);
      await residenceRepo().update(spot.id, {
        deal_spot_heat: newHeat,
        deal_spot_last_tick_at: new Date(),
      });

      // Phase 16 (2026-04-22) — chaleur via HeatService (source unique U4)
      await HeatService.applyToPlayer(spot.player_id, 1, 'point_de_deal_tick', 'deal_spot');

      totalRevenue += revenue;
      processed++;
    }

    return { processed, totalRevenue };
  }

  /**
   * CRON horaire : verifie les risques de raid police sur les deal spots chauds.
   *
   * Si deal_spot_heat >= RAID_HEAT_THRESHOLD et pas de cooldown actif,
   * roll un dice pour raid. Si raid :
   *   - Saisie 50% du stock du drug en inventaire
   *   - +15% chaleur joueur (via HeatService)
   *   - deal_spot desactive
   *   - Notification `point_de_deal_raided` au propriétaire (NotificationService)
   */
  static async processRaidRisk(): Promise<{ raided: number }> {
    const hotSpots = await residenceRepo()
      .createQueryBuilder('r')
      .where('r.deal_spot_active = true')
      .andWhere('r.deal_spot_heat >= :threshold', { threshold: RAID_HEAT_THRESHOLD })
      .getMany();

    let raided = 0;

    for (const spot of hotSpots) {
      // Cooldown check (24h between raids)
      if (spot.deal_spot_last_raid_at) {
        const sinceRaid = Date.now() - new Date(spot.deal_spot_last_raid_at).getTime();
        if (sinceRaid < RAID_COOLDOWN_MS) continue;
      }

      // Roll for raid — probability scales with heat above threshold
      const excessHeat = Math.max(0, (spot.deal_spot_heat ?? 0) - RAID_HEAT_THRESHOLD);
      const raidChance = Math.min(0.80, RAID_CHANCE_BASE + excessHeat * 0.02);
      if (Math.random() >= raidChance) continue;

      // === RAID ===
      // Seize 50% of drug stock
      if (spot.deal_spot_drug) {
        const stock = await inventoryRepo().findOne({
          where: {
            player_id: spot.player_id,
            item_type: 'drug',
            item_subtype: spot.deal_spot_drug,
          },
        });
        if (stock && stock.quantity > 0) {
          const seized = Math.ceil(stock.quantity * 0.5);
          stock.quantity -= seized;
          if (stock.quantity <= 0) {
            await inventoryRepo().remove(stock);
          } else {
            await inventoryRepo().save(stock);
          }
        }
      }

      // Phase 16 (2026-04-22) — chaleur via HeatService (source unique U4)
      await HeatService.applyToPlayer(spot.player_id, 15, 'point_de_deal_raid', 'police');

      // Deactivate the deal spot
      await residenceRepo().update(spot.id, {
        deal_spot_active: false,
        deal_spot_drug: null,
        deal_spot_heat: 0,
        deal_spot_last_raid_at: new Date(),
      });

      // Phase 16 (2026-04-22) — notif propriétaire (U10)
      await NotificationService.create({
        player_id: spot.player_id,
        type: 'point_de_deal_raided',
        title: 'Point de deal raidé',
        message: `La police a fait un raid sur votre point de deal (résidence). 50 % du stock a été saisi et la chaleur grimpe de +15.`,
        link: `residence:${spot.id}`,
      });

      raided++;
    }

    return { raided };
  }

  /**
   * Retourne les infos d'un deal spot actif (pour l'API / frontend).
   */
  static async getSpotInfo(residenceId: string): Promise<{
    active: boolean;
    drug?: string;
    heat?: number;
    activated_at?: Date;
    revenue_per_hour?: number;
  } | null> {
    const res = await residenceRepo().findOne({ where: { id: residenceId } });
    if (!res) return null;
    if (!res.deal_spot_active) return { active: false };

    const rate = getDealingRate(res.deal_spot_drug ?? '');
    const drugDef = DRUGS.find(d => d.name.toLowerCase() === (res.deal_spot_drug ?? '').toLowerCase());
    const revenuePerHour = rate && drugDef
      ? rate.quota_per_gangster_per_hour * FIXED_SPOT_GANGSTER_EQUIV * drugDef.retail_price
      : 0;

    return {
      active: true,
      drug: res.deal_spot_drug ?? undefined,
      heat: res.deal_spot_heat,
      activated_at: res.deal_spot_activated_at ?? undefined,
      revenue_per_hour: revenuePerHour,
    };
  }
}
