import { AppDataSource } from '../config/database';
import { PlayerBalances } from '../models/PlayerBalances';
import { Player } from '../models/Player';
import { BourseService } from './bourse.service';
import { TransactionService } from './transaction.service';
import {
  COMMISSION_LAUNDERING,
  COMMISSION_DAGAZ_SELL,
  COMMISSION_DAGAZ_BUY,
  COMMISSION_QUINT_BUREAU,
  EXCHANGE_PASS_TIER,
  EXCHANGE_PASS_REDUCTION,
  EXCHANGE_MIN_AMOUNT,
  EXCHANGE_MAX_AMOUNT,
  EXCHANGE_COOLDOWN_SECONDS,
} from '../constants/exchange';

/** Devises échangeables au Bureau de Change */
export type ExchangeCurrency = 'infinite_light' | 'infinite_shadow' | 'dagaz' | 'quintessence';

/**
 * Cooldown anti-exploit — persiste en DB via PlayerBalances.last_exchange_at.
 * Survit aux restarts serveur et fonctionne multi-instance.
 */

/**
 * Bureau de Change — Service d'échange de devises
 *
 * POI type 'service', 1 par zone (20 zones françaises).
 * Le joueur doit être physiquement dans la zone pour échanger.
 *
 * Échanges supportés :
 *   - Light ↔ Shadow (blanchiment / noircissement) : taux 1:1 + commission 5%
 *   - Infinites → Dagaz (achat premium) : taux dynamique couplé Bourse
 *   - Dagaz → Infinites (vente premium) : taux dynamique couplé Bourse
 *   - Infinites ↔ Quintessence : via Bourse + surcharge Bureau 1%
 *
 * Notes :
 *   - Dagaz P2P interdit (risque DSP2/MiCA) — uniquement via Bureau
 *   - Pass Tiempo tier ≥ 5 : -50% commission
 */
export class ExchangeService {

  /**
   * Obtenir les taux de change actuels affichés au Bureau
   */
  static async getRates(): Promise<{
    dagaz_rate: number;
    quintessence_cours: number;
    commissions: {
      laundering: number;
      dagaz_buy: number;
      dagaz_sell: number;
      quintessence_surcharge: number;
    };
  }> {
    const [dagazRate, quintCours] = await Promise.all([
      BourseService.getDagazRate(),
      BourseService.getCours(),
    ]);

    return {
      dagaz_rate: dagazRate,
      quintessence_cours: quintCours,
      commissions: {
        laundering: COMMISSION_LAUNDERING,
        dagaz_buy: COMMISSION_DAGAZ_BUY,
        dagaz_sell: COMMISSION_DAGAZ_SELL,
        quintessence_surcharge: COMMISSION_QUINT_BUREAU,
      },
    };
  }

  /**
   * Échange Light ↔ Shadow (blanchiment / noircissement)
   * Taux 1:1, commission 5% (réduite Pass Tiempo)
   */
  static async exchangeLightShadow(
    playerId: string,
    amount: number,
    direction: 'light_to_shadow' | 'shadow_to_light',
  ): Promise<{
    success: boolean;
    input_amount: number;
    output_amount: number;
    commission: number;
    direction: string;
    new_balance: { infinite_light: number; infinite_shadow: number };
  }> {
    ExchangeService.validateAmount(amount);
    await ExchangeService.checkCooldown(playerId);

    const balRepo = AppDataSource.getRepository(PlayerBalances);
    const playerRepo = AppDataSource.getRepository(Player);

    const [balances, player] = await Promise.all([
      balRepo.findOneBy({ player_id: playerId }),
      playerRepo.findOneBy({ id: playerId }),
    ]);
    if (!balances || !player) throw new Error('Joueur introuvable');

    const commRate = ExchangeService.getCommission(COMMISSION_LAUNDERING, player.pass_tiempo_tier);
    const commission = Math.round(amount * commRate);
    const output = amount - commission;

    const fromField = direction === 'light_to_shadow' ? 'infinite_light' : 'infinite_shadow';
    const toField = direction === 'light_to_shadow' ? 'infinite_shadow' : 'infinite_light';

    const currentFrom = Number(balances[fromField]);
    if (currentFrom < amount) {
      throw new Error(`Solde ${fromField} insuffisant : ${currentFrom}, besoin de ${amount}`);
    }

    (balances[fromField] as any) = currentFrom - amount;
    (balances[toField] as any) = Number(balances[toField]) + output;
    await balRepo.save(balances);

    // Log transactions
    const label = direction === 'light_to_shadow' ? 'Blanchiment' : 'Noircissement';
    await TransactionService.log({
      player_id: playerId,
      category: 'exchange',
      type: 'out',
      amount,
      currency: fromField,
      description: `${label} Bureau de Change`,
    });
    await TransactionService.log({
      player_id: playerId,
      category: 'exchange',
      type: 'in',
      amount: output,
      currency: toField,
      description: `${label} Bureau de Change`,
    });

    await ExchangeService.setCooldown(playerId);

    return {
      success: true,
      input_amount: amount,
      output_amount: output,
      commission,
      direction,
      new_balance: {
        infinite_light: Number(balances.infinite_light),
        infinite_shadow: Number(balances.infinite_shadow),
      },
    };
  }

  /**
   * Acheter des Dagaz avec des Infinites (∞ → ᛞ)
   * Taux dynamique couplé à la Bourse + commission 3%
   */
  static async buyDagaz(
    playerId: string,
    dagazAmount: number,
    currency: 'infinite_light' | 'infinite_shadow' = 'infinite_light',
  ): Promise<{
    success: boolean;
    dagaz_bought: number;
    cost: number;
    commission: number;
    rate: number;
    new_balance: any;
  }> {
    if (dagazAmount <= 0 || !Number.isFinite(dagazAmount) || dagazAmount !== Math.floor(dagazAmount)) {
      throw new Error('Montant Dagaz invalide (entier positif requis)');
    }
    await ExchangeService.checkCooldown(playerId);

    const balRepo = AppDataSource.getRepository(PlayerBalances);
    const playerRepo = AppDataSource.getRepository(Player);

    const [balances, player, dagazRate] = await Promise.all([
      balRepo.findOneBy({ player_id: playerId }),
      playerRepo.findOneBy({ id: playerId }),
      BourseService.getDagazRate(),
    ]);
    if (!balances || !player) throw new Error('Joueur introuvable');

    const commRate = ExchangeService.getCommission(COMMISSION_DAGAZ_BUY, player.pass_tiempo_tier);
    const rawCost = Math.round(dagazAmount * dagazRate);
    const commission = Math.round(rawCost * commRate);
    const totalCost = rawCost + commission;

    ExchangeService.validateAmount(totalCost);

    const currentBalance = Number(balances[currency]);
    if (currentBalance < totalCost) {
      throw new Error(`Solde ${currency} insuffisant : ${currentBalance}, besoin de ${totalCost}`);
    }

    (balances[currency] as any) = currentBalance - totalCost;
    balances.dagaz = Number(balances.dagaz) + dagazAmount;
    await balRepo.save(balances);

    await TransactionService.log({
      player_id: playerId,
      category: 'exchange',
      type: 'out',
      amount: totalCost,
      currency,
      description: `Achat ${dagazAmount}ᛞ au Bureau de Change`,
    });

    await ExchangeService.setCooldown(playerId);

    return {
      success: true,
      dagaz_bought: dagazAmount,
      cost: totalCost,
      commission,
      rate: dagazRate,
      new_balance: {
        [currency]: balances[currency],
        dagaz: balances.dagaz,
      },
    };
  }

  /**
   * Vendre des Dagaz contre des Infinites (ᛞ → ∞)
   * Taux dynamique + commission 2%
   */
  static async sellDagaz(
    playerId: string,
    dagazAmount: number,
    currency: 'infinite_light' | 'infinite_shadow' = 'infinite_light',
  ): Promise<{
    success: boolean;
    dagaz_sold: number;
    revenue: number;
    commission: number;
    rate: number;
    new_balance: any;
  }> {
    if (dagazAmount <= 0 || !Number.isFinite(dagazAmount) || dagazAmount !== Math.floor(dagazAmount)) {
      throw new Error('Montant Dagaz invalide (entier positif requis)');
    }
    await ExchangeService.checkCooldown(playerId);

    const balRepo = AppDataSource.getRepository(PlayerBalances);
    const playerRepo = AppDataSource.getRepository(Player);

    const [balances, player, dagazRate] = await Promise.all([
      balRepo.findOneBy({ player_id: playerId }),
      playerRepo.findOneBy({ id: playerId }),
      BourseService.getDagazRate(),
    ]);
    if (!balances || !player) throw new Error('Joueur introuvable');

    if (Number(balances.dagaz) < dagazAmount) {
      throw new Error(`Solde ᛞ insuffisant : ${balances.dagaz}, besoin de ${dagazAmount}`);
    }

    const commRate = ExchangeService.getCommission(COMMISSION_DAGAZ_SELL, player.pass_tiempo_tier);
    const rawRevenue = Math.round(dagazAmount * dagazRate);
    const commission = Math.round(rawRevenue * commRate);
    const netRevenue = rawRevenue - commission;

    balances.dagaz = Number(balances.dagaz) - dagazAmount;
    (balances[currency] as any) = Number(balances[currency]) + netRevenue;
    await balRepo.save(balances);

    await TransactionService.log({
      player_id: playerId,
      category: 'exchange',
      type: 'in',
      amount: netRevenue,
      currency,
      description: `Vente ${dagazAmount}ᛞ au Bureau de Change`,
    });

    await ExchangeService.setCooldown(playerId);

    return {
      success: true,
      dagaz_sold: dagazAmount,
      revenue: netRevenue,
      commission,
      rate: dagazRate,
      new_balance: {
        [currency]: balances[currency],
        dagaz: balances.dagaz,
      },
    };
  }

  /**
   * Échanger Infinites ↔ Quintessence au Bureau de Change
   * Utilise le cours Bourse + surcharge Bureau 1%
   * (Pratique : pas besoin d'aller sur la Bourse, mais légèrement plus cher)
   */
  static async exchangeQuintessence(
    playerId: string,
    amount: number,
    direction: 'buy' | 'sell',
    currency: 'infinite_light' | 'infinite_shadow' = 'infinite_light',
  ): Promise<{
    success: boolean;
    direction: string;
    quintessence_amount: number;
    infinite_amount: number;
    commission: number;
    bureau_surcharge: number;
    cours: number;
    new_balance: any;
  }> {
    await ExchangeService.checkCooldown(playerId);

    // Deléguer à la Bourse pour le trade principal
    if (direction === 'buy') {
      if (amount <= 0) throw new Error('Montant invalide');
      const result = await BourseService.buy(playerId, amount, currency);

      // Surcharge Bureau (commission additionnelle prélevée en ∞)
      const balRepo = AppDataSource.getRepository(PlayerBalances);
      const playerRepo = AppDataSource.getRepository(Player);
      const [balances, player] = await Promise.all([
        balRepo.findOneBy({ player_id: playerId }),
        playerRepo.findOneBy({ id: playerId }),
      ]);
      if (!balances || !player) throw new Error('Joueur introuvable');

      const surchargeRate = ExchangeService.getCommission(COMMISSION_QUINT_BUREAU, player.pass_tiempo_tier);
      const surcharge = Math.round(result.cost * surchargeRate);

      if (Number(balances[currency]) < surcharge) {
        throw new Error(`Fonds insuffisants pour la surcharge Bureau (${surcharge} ∞ requis)`);
      }

      (balances[currency] as any) = Number(balances[currency]) - surcharge;
      await balRepo.save(balances);

      await ExchangeService.setCooldown(playerId);

      return {
        success: true,
        direction: 'buy',
        quintessence_amount: amount,
        infinite_amount: result.cost + surcharge,
        commission: result.commission,
        bureau_surcharge: surcharge,
        cours: result.cours,
        new_balance: {
          [currency]: balances[currency],
          quintessence: balances.quintessence,
        },
      };
    } else {
      // Sell quintessence
      if (amount <= 0) throw new Error('Montant invalide');
      const result = await BourseService.sell(playerId, amount, currency);

      // Surcharge Bureau (prélevée sur le revenu)
      const balRepo = AppDataSource.getRepository(PlayerBalances);
      const playerRepo = AppDataSource.getRepository(Player);
      const [balances, player] = await Promise.all([
        balRepo.findOneBy({ player_id: playerId }),
        playerRepo.findOneBy({ id: playerId }),
      ]);
      if (!balances || !player) throw new Error('Joueur introuvable');

      const surchargeRate = ExchangeService.getCommission(COMMISSION_QUINT_BUREAU, player.pass_tiempo_tier);
      const surcharge = Math.round(result.revenue * surchargeRate);

      (balances[currency] as any) = Math.max(0, Number(balances[currency]) - surcharge);
      await balRepo.save(balances);

      await ExchangeService.setCooldown(playerId);

      return {
        success: true,
        direction: 'sell',
        quintessence_amount: amount,
        infinite_amount: result.revenue - surcharge,
        commission: result.commission,
        bureau_surcharge: surcharge,
        cours: result.cours,
        new_balance: {
          [currency]: balances[currency],
          quintessence: balances.quintessence,
        },
      };
    }
  }

  // ==================== UTILITAIRES ====================

  /** Calcule la commission effective (réduite si Pass Tiempo) */
  private static getCommission(baseRate: number, passTier: number): number {
    if (passTier >= EXCHANGE_PASS_TIER) {
      return baseRate * (1 - EXCHANGE_PASS_REDUCTION);
    }
    return baseRate;
  }

  /** Valide le montant d'échange */
  private static validateAmount(amount: number): void {
    if (!Number.isFinite(amount) || amount <= 0) {
      throw new Error('Montant invalide');
    }
    if (amount < EXCHANGE_MIN_AMOUNT) {
      throw new Error(`Montant minimum : ${EXCHANGE_MIN_AMOUNT} ∞`);
    }
    if (amount > EXCHANGE_MAX_AMOUNT) {
      throw new Error(`Montant maximum par transaction : ${EXCHANGE_MAX_AMOUNT} ∞`);
    }
  }

  /** Vérifie le cooldown anti-exploit (persistant en DB) */
  private static async checkCooldown(playerId: string): Promise<void> {
    const balanceRepo = AppDataSource.getRepository(PlayerBalances);
    const balance = await balanceRepo.findOne({ where: { player_id: playerId } });
    if (balance?.last_exchange_at) {
      const elapsed = (Date.now() - new Date(balance.last_exchange_at).getTime()) / 1000;
      if (elapsed < EXCHANGE_COOLDOWN_SECONDS) {
        const remaining = Math.ceil(EXCHANGE_COOLDOWN_SECONDS - elapsed);
        throw new Error(`Veuillez patienter ${remaining}s avant le prochain échange`);
      }
    }
  }

  /** Enregistre le timestamp du dernier echange en DB */
  private static async setCooldown(playerId: string): Promise<void> {
    const balanceRepo = AppDataSource.getRepository(PlayerBalances);
    await balanceRepo.update({ player_id: playerId }, { last_exchange_at: new Date() });
  }
}
