import { AppDataSource } from '../config/database';
import { NpcConfig } from '../models/NpcConfig';
import { Player } from '../models/Player';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerInventory } from '../models/PlayerInventory';
import { Listing, MarketType } from '../models/Listing';
import { PlayerGauges } from '../models/PlayerGauges';
import { PlayerHealth } from '../models/PlayerHealth';

/**
 * EconomyService — Gestion de l'économie automatisée
 *
 * Responsabilités:
 * - Restock des PNJ marchands
 * - Calcul offre/demande → ajustement des prix
 * - Raréfaction cyclique de certaines denrées
 * - Création automatique de listings PNJ
 * - Gestion du flux PIB → items consommables/achetables
 */
export class EconomyService {

  /**
   * Créer un joueur PNJ avec son profil, balances, etc.
   */
  static async createNpc(data: {
    username: string;
    npc_role: string;
    profile_image_url?: string;
    market_type: 'white' | 'black';
    product_category: string;
    product_templates: Array<{
      item_type: string;
      item_subtype: string;
      base_quality: number;
      quality_variance: number;
      base_price: number;
      price_variance: number;
      rarity: number;
    }>;
    min_listings?: number;
    max_listings?: number;
    restock_interval?: number;
  }) {
    const playerRepo = AppDataSource.getRepository(Player);
    const balancesRepo = AppDataSource.getRepository(PlayerBalances);
    const gaugesRepo = AppDataSource.getRepository(PlayerGauges);
    const healthRepo = AppDataSource.getRepository(PlayerHealth);
    const npcRepo = AppDataSource.getRepository(NpcConfig);

    // Créer le joueur PNJ
    const npcPlayer = playerRepo.create({
      username: data.username,
      email: `npc_${data.username.toLowerCase().replace(/\s+/g, '_')}@mafiaz.world`,
      password_hash: null,
      oauth_provider: 'email',
      is_npc: true,
      npc_role: data.npc_role,
      profile_image_url: data.profile_image_url || null,
      is_active: true,
      onboarding_completed: true,
    });
    const saved = await playerRepo.save(npcPlayer);

    // Créer les données associées
    await balancesRepo.save(balancesRepo.create({
      player_id: saved.id,
      infinite_light: 1000000, // Les PNJ ont des fonds illimités en pratique
      infinite_shadow: 0,
      dagaz: 0,
      quintessence: 0,
    }));

    await gaugesRepo.save(gaugesRepo.create({ player_id: saved.id }));
    await healthRepo.save(healthRepo.create({ player_id: saved.id }));

    // Créer la config NPC
    const config = npcRepo.create({
      player_id: saved.id,
      product_category: data.product_category as any,
      market_type: data.market_type,
      product_templates: data.product_templates,
      min_active_listings: data.min_listings ?? 3,
      max_active_listings: data.max_listings ?? 10,
      restock_interval_minutes: data.restock_interval ?? 60,
      is_active: true,
    });
    await npcRepo.save(config);

    return { player: saved, config };
  }

  /**
   * Restock un PNJ: crée des items dans son inventaire puis des listings
   */
  static async restockNpc(configId: string) {
    const npcRepo = AppDataSource.getRepository(NpcConfig);
    const inventoryRepo = AppDataSource.getRepository(PlayerInventory);
    const listingRepo = AppDataSource.getRepository(Listing);

    const config = await npcRepo.findOne({ where: { id: configId }, relations: ['player'] });
    if (!config || !config.is_active) return;

    // Compter les listings actifs
    const activeCount = await listingRepo.count({
      where: { seller_id: config.player_id, status: 'open' as any },
    });

    if (activeCount >= config.max_active_listings) return;

    const toCreate = Math.min(
      config.max_active_listings - activeCount,
      Math.max(0, config.min_active_listings - activeCount) + Math.floor(Math.random() * 3),
    );

    for (let i = 0; i < toCreate; i++) {
      // Sélectionner un template selon la rareté
      const template = EconomyService.pickTemplate(config.product_templates);
      if (!template) continue;

      // Calculer qualité et prix avec variance
      const quality = Math.max(1, Math.min(5, Math.round(
        template.base_quality + (Math.random() * 2 - 1) * template.quality_variance,
      )));
      const price = Math.max(1, Math.round(
        template.base_price * config.price_multiplier
        + (Math.random() * 2 - 1) * template.price_variance,
      ));

      // Créer l'item dans l'inventaire du PNJ
      const item = inventoryRepo.create({
        player_id: config.player_id,
        item_type: template.item_type as any,
        item_subtype: template.item_subtype,
        quantity: 1,
        quality,
        is_listed: true,
      });
      const savedItem = await inventoryRepo.save(item);

      // Déterminer la catégorie de listing
      const categoryMap: Record<string, string> = {
        weapon: 'item_weapon',
        drug: 'item_drug',
        food: 'item_food',
        vehicle: 'item_vehicle',
        document: 'item_document',
        armor: 'item_armor',
        phone: 'item_phone',
        other: 'item_other',
      };

      // Créer le listing
      const listing = listingRepo.create({
        seller_id: config.player_id,
        title: `${template.item_subtype} ${quality > 3 ? '(Premium)' : ''}`.trim(),
        market_type: config.market_type as MarketType,
        category: (categoryMap[template.item_type] || 'item_other') as any,
        listing_data: {
          item_type: template.item_type,
          item_subtype: template.item_subtype,
          quantity: 1,
          quality,
          inventory_id: savedItem.id,
        },
        suggested_value: price,
        status: 'open',
      });
      const savedListing = await listingRepo.save(listing);

      // Lier l'item au listing
      await inventoryRepo.update(savedItem.id, { listing_id: savedListing.id });
    }

    // Mettre à jour le dernier restock
    config.last_restock_at = new Date();
    await npcRepo.save(config);
  }

  /**
   * Sélectionner un template selon la probabilité de rareté
   */
  private static pickTemplate(templates: NpcConfig['product_templates']) {
    const roll = Math.random();
    let cumulative = 0;
    const totalRarity = templates.reduce((s, t) => s + t.rarity, 0);
    for (const t of templates) {
      cumulative += t.rarity / totalRarity;
      if (roll <= cumulative) return t;
    }
    return templates[templates.length - 1];
  }

  /**
   * Ajuster les prix selon l'offre/demande
   * Appelé périodiquement (ex: toutes les heures)
   */
  static async adjustMarketPrices() {
    const npcRepo = AppDataSource.getRepository(NpcConfig);
    const listingRepo = AppDataSource.getRepository(Listing);

    const configs = await npcRepo.find({ where: { is_active: true } });

    for (const config of configs) {
      // Compter les listings vendus récemment (transmitted dans les 24h)
      const recentSales = await listingRepo
        .createQueryBuilder('l')
        .where('l.seller_id = :pid', { pid: config.player_id })
        .andWhere('l.status = :st', { st: 'transmitted' })
        .andWhere('l.transmitted_at > NOW() - INTERVAL \'24 hours\'')
        .getCount();

      // Compter les listings actifs
      const activeListings = await listingRepo.count({
        where: { seller_id: config.player_id, status: 'open' as any },
      });

      // Forte demande (beaucoup de ventes) → prix monte
      // Faible demande (stock qui s'accumule) → prix baisse
      const demandRatio = activeListings > 0
        ? recentSales / activeListings
        : 0;

      if (demandRatio > 0.7) {
        // Forte demande → augmenter de 5-15%
        config.price_multiplier = Math.min(3.0, config.price_multiplier * (1 + 0.05 + Math.random() * 0.10));
      } else if (demandRatio < 0.2 && activeListings > config.min_active_listings) {
        // Surplus → baisser de 5-10%
        config.price_multiplier = Math.max(0.3, config.price_multiplier * (1 - 0.05 - Math.random() * 0.05));
      } else {
        // Tendance vers 1.0 (normalisation lente)
        config.price_multiplier = config.price_multiplier * 0.95 + 1.0 * 0.05;
      }

      await npcRepo.save(config);
    }
  }

  /**
   * Restock automatique de tous les PNJ éligibles
   * À appeler via un CRON job (ex: toutes les 15 minutes)
   */
  static async processAllRestocks() {
    const npcRepo = AppDataSource.getRepository(NpcConfig);
    const configs = await npcRepo.find({ where: { is_active: true } });

    const now = new Date();
    let restocked = 0;

    for (const config of configs) {
      const lastRestock = config.last_restock_at
        ? new Date(config.last_restock_at).getTime()
        : 0;
      const intervalMs = config.restock_interval_minutes * 60 * 1000;

      if (now.getTime() - lastRestock >= intervalMs) {
        await EconomyService.restockNpc(config.id);
        restocked++;
      }
    }

    return { processed: configs.length, restocked };
  }

  /**
   * Raréfaction cyclique: certaines catégories deviennent rares périodiquement
   * Simule les pénuries naturelles du marché
   */
  static async applyCyclicScarcity() {
    const npcRepo = AppDataSource.getRepository(NpcConfig);
    const configs = await npcRepo.find({ where: { is_active: true } });

    // Cycle basé sur le jour de l'année pour des variations naturelles
    const dayOfYear = Math.floor(
      (Date.now() - new Date(new Date().getFullYear(), 0, 0).getTime()) / 86400000,
    );

    // Chaque catégorie a son propre cycle de rareté
    const scarcityCycles: Record<string, { period: number; amplitude: number }> = {
      drogues: { period: 7, amplitude: 0.6 },     // Cycle court, forte amplitude
      armes: { period: 14, amplitude: 0.4 },       // Cycle moyen
      nourriture: { period: 3, amplitude: 0.2 },   // Cycle très court, faible amplitude
      alcool: { period: 10, amplitude: 0.5 },
      vehicules: { period: 30, amplitude: 0.3 },   // Cycle long
      documents: { period: 21, amplitude: 0.3 },
    };

    for (const config of configs) {
      const cycle = scarcityCycles[config.product_category];
      if (!cycle) continue;

      // Onde sinusoïdale pour la rareté
      const phase = (dayOfYear % cycle.period) / cycle.period * Math.PI * 2;
      const scarcityFactor = 1 + Math.sin(phase) * cycle.amplitude;

      // Ajuster le nombre max de listings (arrondi)
      const baseMax = config.max_active_listings;
      const adjustedMax = Math.max(1, Math.round(baseMax * scarcityFactor));
      config.max_active_listings = adjustedMax;

      // On ajuste aussi le price_multiplier
      // Quand c'est rare → prix monte, quand c'est abondant → prix baisse
      const priceFactor = 1 / scarcityFactor; // Inverse: rare = cher
      config.price_multiplier = Math.max(0.3, Math.min(3.0,
        config.price_multiplier * 0.8 + priceFactor * 0.2,
      ));

      await npcRepo.save(config);
    }
  }
}
