import { AppDataSource } from '../config/database';
import { Business } from '../models/Business';
import { PlayerBalances } from '../models/PlayerBalances';
import { Player } from '../models/Player';
import { POI } from '../models/POI';
import { TransactionService } from './transaction.service';

const businessRepo = () => AppDataSource.getRepository(Business);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const poiRepo = () => AppDataSource.getRepository(POI);
const playerRepo = () => AppDataSource.getRepository(Player);

function randomInt(min: number, max: number): number {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 * Service Casino (Phase 4, 2026-04-20) — amenity=casino.
 *
 * 1 seul casino auto-généré par joueur (rayon 3km du Point de Territoire) lors
 * de initialize-zone. Prix d'achat 25M à 3B selon CA historique.
 *
 * Propriétaire peut :
 *   - Blanchir ∞ shadow → ∞ light gratuitement, cap 100 000/mois
 *   - Voir l'historique C.A. quotidien (revenus 3-9k net 2-6k coûts)
 *
 * CRON quotidien (minuit Paris) : calcule revenus/couts du jour, append à
 * casino_revenue_history (365 derniers jours max).
 */
export class CasinoService {
  static readonly MONTHLY_LAUNDER_LIMIT = 100_000;
  static readonly DAILY_REVENUE_MIN = 3_000;
  static readonly DAILY_REVENUE_MAX = 9_000;
  static readonly DAILY_COST_MIN = 2_000;
  static readonly DAILY_COST_MAX = 6_000;
  static readonly PURCHASE_PRICE_MIN = 25_000_000;
  static readonly PURCHASE_PRICE_MAX = 3_000_000_000;
  static readonly GENERATION_RADIUS_KM = 3.0;

  /**
   * Auto-génère un casino pour le joueur (1/joueur). Idempotent.
   * Positionné en disque [0..3] km du start_lat/lon.
   */
  static async autoGenerateForPlayer(playerId: string): Promise<Business | null> {
    const player = await playerRepo().findOneBy({ id: playerId });
    if (!player?.start_lat || !player?.start_lon || !player.selected_zone_id) return null;

    // 1 seul casino par joueur
    const existing = await businessRepo().findOne({
      where: { player_id: player.id, type: 'casino' as any },
    });
    if (existing) return existing;

    // Position aléatoire en disque [0..3] km
    const distKm = Math.random() * CasinoService.GENERATION_RADIUS_KM;
    const angle = Math.random() * 2 * Math.PI;
    const lat0 = Number(player.start_lat);
    const lon0 = Number(player.start_lon);
    const dLat = (distKm * 1000 * Math.cos(angle)) / 111000;
    const dLon = (distKm * 1000 * Math.sin(angle)) / (111000 * Math.cos(lat0 * Math.PI / 180));

    // Prix cohérent avec le tier initial du joueur (petit casino au lancement)
    const purchasePrice = CasinoService.PURCHASE_PRICE_MIN;

    const casino = businessRepo().create({
      player_id: player.id,  // temporairement "possédé" par le joueur pour facilité de dev
      name: `Casino de ${player.username}`,
      type: 'casino' as any,
      category: 'business_service',
      level: 1,
      revenue_per_day: 0,
      surface_m2: 200,
      storage_capacity_kg: 0,
      current_stock_kg: 0,
      production_limit_per_day: 0,
      legal_specialization: null,
      purchase_price: purchasePrice,
      sale_value: Math.round(purchasePrice * 0.7),
      tenant_id: null,
      employee_count: 8,
      max_employees: 20,
      daily_sales_limit: 0,
      location_lat: lat0 + dLat,
      location_lon: lon0 + dLon,
      zone_id: player.selected_zone_id,
      is_legal: true,
      heat_generated: 0,
      monthly_launder_used: 0,
      launder_month_cycle: null,
      casino_revenue_history: [],
    });
    const saved = await businessRepo().save(casino);

    // POI miroir (icon=casino)
    await poiRepo().save(poiRepo().create({
      zone_id: player.selected_zone_id,
      type: 'business' as any,
      name: saved.name,
      location_lat: Number(saved.location_lat),
      location_lon: Number(saved.location_lon),
      entity_id: saved.id,
      icon: 'casino',
      is_visible: true,
      category: 'business_service',
    }));

    return saved;
  }

  /**
   * Blanchiment casino : débit shadow → crédit light gratuit, cap 100k/mois.
   */
  static async launderMoney(
    playerId: string,
    casinoBusinessId: string,
    amountShadow: number,
  ): Promise<{
    credited: number;
    monthly_used: number;
    monthly_remaining: number;
    cycle: string;
  }> {
    if (!Number.isFinite(amountShadow) || amountShadow <= 0) throw new Error('Montant invalide');

    const biz = await businessRepo().findOneBy({ id: casinoBusinessId });
    if (!biz) throw new Error('Casino introuvable');
    if (biz.type !== 'casino') throw new Error('Ce commerce n\'est pas un casino');
    if (biz.player_id !== playerId) throw new Error('Vous ne possédez pas ce casino');

    const now = new Date();
    const cycle = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;

    // Reset si nouveau mois
    if (biz.launder_month_cycle !== cycle) {
      biz.launder_month_cycle = cycle;
      biz.monthly_launder_used = 0;
    }

    const remaining = CasinoService.MONTHLY_LAUNDER_LIMIT - biz.monthly_launder_used;
    if (amountShadow > remaining) {
      throw new Error(`Limite mensuelle dépassée (${remaining} ∞ restants en ${cycle})`);
    }

    return AppDataSource.transaction(async tx => {
      const bal = await tx.getRepository(PlayerBalances).findOneBy({ player_id: playerId });
      if (!bal) throw new Error('Solde introuvable');
      if (Number(bal.infinite_shadow) < amountShadow) {
        throw new Error('Solde shadow insuffisant');
      }
      await tx.getRepository(PlayerBalances).decrement({ player_id: playerId }, 'infinite_shadow', amountShadow);
      await tx.getRepository(PlayerBalances).increment({ player_id: playerId }, 'infinite_light', amountShadow);

      biz.monthly_launder_used += amountShadow;
      await tx.getRepository(Business).save(biz);

      await TransactionService.log({
        player_id: playerId, category: 'exchange', type: 'out',
        amount: amountShadow, currency: 'infinite_shadow',
        description: `Blanchiment casino ${biz.name}`,
      });

      return {
        credited: amountShadow,
        monthly_used: biz.monthly_launder_used,
        monthly_remaining: CasinoService.MONTHLY_LAUNDER_LIMIT - biz.monthly_launder_used,
        cycle,
      };
    });
  }

  /**
   * CRON quotidien : calcule revenus/coûts du jour pour chaque casino,
   * crédite net dans cash_register, append à casino_revenue_history.
   */
  static async dailyRevenueTick(): Promise<{ processed: number; totalNet: number }> {
    const casinos = await businessRepo().find({ where: { type: 'casino' as any } });
    let totalNet = 0;
    for (const c of casinos) {
      if (c.is_permanent_shutdown) continue;
      const gross = randomInt(CasinoService.DAILY_REVENUE_MIN, CasinoService.DAILY_REVENUE_MAX);
      const costs = randomInt(CasinoService.DAILY_COST_MIN, CasinoService.DAILY_COST_MAX);
      const net = gross - costs;
      c.cash_register = (c.cash_register ?? 0) + net;

      const history = Array.isArray(c.casino_revenue_history) ? c.casino_revenue_history : [];
      history.push({ date: new Date().toISOString().slice(0, 10), gross, costs, net });
      while (history.length > 365) history.shift();
      c.casino_revenue_history = history;

      await businessRepo().save(c);
      totalNet += net;
    }
    return { processed: casinos.length, totalNet };
  }
}
