import { AppDataSource } from '../config/database';
import { ProductionBatch, ProductionChainType, ProductionStage } from '../models/ProductionBatch';
import { Business } from '../models/Business';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerInventory } from '../models/PlayerInventory';
import { PRODUCTION_CHAINS, COST_RATIOS } from '../constants/production-chains';
import { DRUGS } from '../constants/drugs';

const batchRepo = () => AppDataSource.getRepository(ProductionBatch);
const businessRepo = () => AppDataSource.getRepository(Business);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const inventoryRepo = () => AppDataSource.getRepository(PlayerInventory);

export class ProductionService {

  /** Get production chain definitions */
  static getChains() {
    return PRODUCTION_CHAINS;
  }

  /** Get cost ratios */
  static getCostRatios() {
    return COST_RATIOS;
  }

  /** Get all active batches for a player */
  static async getPlayerBatches(playerId: string) {
    return batchRepo().find({
      where: { player_id: playerId },
      order: { created_at: 'DESC' },
    });
  }

  /** Start a new production batch */
  static async startBatch(playerId: string, data: {
    business_id: string;
    chain_type: ProductionChainType;
    product_name: string;
    quantity_kg: number;
  }) {
    // Verify business ownership
    const business = await businessRepo().findOne({
      where: { id: data.business_id, player_id: playerId },
    });
    if (!business) throw new Error('Commerce introuvable ou ne vous appartient pas');

    // Check production limits
    if (business.production_limit_per_day && business.production_limit_per_day > 0) {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const todayBatches = await batchRepo()
        .createQueryBuilder('b')
        .where('b.business_id = :bid', { bid: data.business_id })
        .andWhere('b.created_at >= :today', { today })
        .getMany();
      const todayKg = todayBatches.reduce((sum, b) => sum + b.quantity_kg, 0);
      if (todayKg + data.quantity_kg > business.production_limit_per_day) {
        throw new Error(`Limite de production journalière dépassée (${business.production_limit_per_day} kg/jour)`);
      }
    }

    // Calculate production cost
    let costPerUnit: number;
    let durationHours: number;
    let yieldRate: number;

    if (data.chain_type === 'drogue') {
      const drug = DRUGS.find(d => d.name.toLowerCase() === data.product_name.toLowerCase());
      if (!drug) throw new Error('Produit introuvable dans le catalogue drogues');
      costPerUnit = drug.production_cost;
      durationHours = 6; // Default drug production time
      yieldRate = 80;
    } else {
      const chain = PRODUCTION_CHAINS.find(c => c.type === data.chain_type);
      if (!chain) throw new Error('Chaîne de production invalide');
      const firstStage = chain.stages[0];
      costPerUnit = firstStage.cost_per_unit;
      durationHours = firstStage.duration_hours;
      yieldRate = Math.round(firstStage.yield_rate * 100);
    }

    const totalCost = Math.ceil(costPerUnit * data.quantity_kg);

    // Check funds
    const balance = await balancesRepo().findOneBy({ player_id: playerId });
    if (!balance) throw new Error('Solde introuvable');

    const currency = data.chain_type === 'drogue' ? 'infinite_shadow' : 'infinite_light';
    if (Number(balance[currency]) < totalCost) {
      throw new Error(`Fonds insuffisants. Coût: ${totalCost} ∞`);
    }

    // Debit
    await balancesRepo().decrement({ player_id: playerId }, currency, totalCost);

    // Create batch
    const now = new Date();
    const completesAt = new Date(now.getTime() + durationHours * 60 * 60 * 1000);

    const batch = batchRepo().create({
      player_id: playerId,
      business_id: data.business_id,
      chain_type: data.chain_type,
      stage: 'processing',
      product_name: data.product_name,
      quantity_kg: data.quantity_kg,
      production_cost: totalCost,
      started_at: now,
      completes_at: completesAt,
      yield_rate: yieldRate,
    });

    return batchRepo().save(batch);
  }

  /** Collect a finished batch → inventory */
  static async collectBatch(playerId: string, batchId: string) {
    const batch = await batchRepo().findOne({
      where: { id: batchId, player_id: playerId },
    });
    if (!batch) throw new Error('Lot de production introuvable');
    if (batch.stage === 'delivered') throw new Error('Lot déjà récupéré');
    if (batch.completes_at && new Date() < batch.completes_at) {
      throw new Error('Production pas encore terminée');
    }

    // Calculate effective output
    const effectiveQty = Math.ceil(batch.quantity_kg * batch.yield_rate / 100);
    const weightGrams = effectiveQty * 1000;

    // Add to player inventory
    const itemType = batch.chain_type === 'drogue' ? 'drug' : 'other';
    const item = inventoryRepo().create({
      player_id: playerId,
      item_type: itemType as any,
      item_subtype: batch.product_name,
      quantity: effectiveQty,
      quality: 3, // Base quality
      storage_condition: 'stored',
      storage_location_id: batch.business_id,
      weight_grams: weightGrams,
    });
    await inventoryRepo().save(item);

    // Update batch status
    batch.stage = 'delivered';
    await batchRepo().save(batch);

    return { batch, item, effective_quantity_kg: effectiveQty };
  }

  /** Auto-convert weight display: g → kg → tonnes */
  static formatWeight(grams: number): string {
    if (grams >= 1_000_000) {
      return `${(grams / 1_000_000).toFixed(2)} t`;
    }
    if (grams >= 1000) {
      return `${(grams / 1000).toFixed(2)} kg`;
    }
    return `${grams} g`;
  }

  /** Calculate selling price based on channel and cost ratios */
  static calculateSellingPrice(productionCost: number, channel: 'white_wholesale' | 'black_wholesale' | 'retail'): number {
    switch (channel) {
      case 'white_wholesale':
        return productionCost * COST_RATIOS.wholesale_white;
      case 'black_wholesale':
        return productionCost * COST_RATIOS.wholesale_black;
      case 'retail':
        return productionCost * COST_RATIOS.wholesale_white * COST_RATIOS.retail_markup;
    }
  }
}
