import type { EntityManager } from 'typeorm';
import { AppDataSource } from '../config/database';
import { Business } from '../models/Business';
import { Residence } from '../models/Residence';
import { Vehicle } from '../models/Vehicle';
import { Warehouse } from '../models/Warehouse';
import { PlayerBalances } from '../models/PlayerBalances';
import { Player } from '../models/Player';
import { PlayerInventory, StorageCondition } from '../models/PlayerInventory';
import { TransactionService } from './transaction.service';

const businessRepo = () => AppDataSource.getRepository(Business);
const residenceRepo = () => AppDataSource.getRepository(Residence);
const vehicleRepo = () => AppDataSource.getRepository(Vehicle);
const warehouseRepo = () => AppDataSource.getRepository(Warehouse);
const inventoryRepo = () => AppDataSource.getRepository(PlayerInventory);

/** Types de localisation supportés pour le transfert d'items (audit 15-04-2026) */
export type StorageLocationType = 'residence' | 'business' | 'warehouse' | 'vehicle' | 'player';

export interface TransferItemParams {
  source_location_type: StorageLocationType;
  source_location_id: string;           // playerId si source_location_type='player'
  destination_location_type: StorageLocationType;
  destination_location_id: string;      // playerId si destination_location_type='player'
  inventory_id: string;                 // PlayerInventory.id
  quantity: number;
}

export interface LocationCapacity {
  location_type: StorageLocationType;
  location_id: string;
  capacity_kg: number;         // Capacité totale en kg
  filled_kg: number;           // Poids réel calculé via SUM inventory (fiable)
  remaining_kg: number;        // capacity_kg - filled_kg, clamped >= 0
  item_count: number;          // nombre de rows d'inventaire stockées
}

/** Limite poids "on_person" (cf. mission.service.ts weightMalus : 35kg max) */
const ON_PERSON_MAX_KG = 35;

export class PropertyService {

  // ── Businesses ──────────────────────────────────────────────

  static async getPlayerBusinesses(playerId: string) {
    return businessRepo().find({
      where: { player_id: playerId },
      order: { created_at: 'DESC' },
    });
  }

  static async getBusinessById(id: string, playerId: string) {
    const business = await businessRepo().findOne({ where: { id } });
    if (!business) return null;
    if (business.player_id !== playerId) return null;
    return business;
  }

  static async createBusiness(playerId: string, data: Partial<Business>) {
    const business = businessRepo().create({
      ...data,
      player_id: playerId,
    });
    return businessRepo().save(business);
  }

  static async updateBusiness(id: string, playerId: string, data: Partial<Business>) {
    const business = await businessRepo().findOne({ where: { id } });
    if (!business) return null;
    if (business.player_id !== playerId) return null;
    Object.assign(business, data);
    return businessRepo().save(business);
  }

  /**
   * Purchase a business from the Municipalite (NPC) or another player.
   * Debits the purchase_price from the buyer's balance and transfers ownership.
   */
  static async purchaseBusiness(businessId: string, buyerId: string): Promise<Business> {
    const business = await businessRepo().findOne({ where: { id: businessId } });
    if (!business) throw new Error('Business introuvable');

    // Verify the seller is NPC (Municipalite) or another player — cannot buy own business
    if (business.player_id === buyerId) throw new Error('Vous possedez deja ce business');

    const price = business.purchase_price;
    if (!price || price <= 0) throw new Error('Ce business n\'est pas a vendre');

    // Check buyer balance
    const balanceRepo = AppDataSource.getRepository(PlayerBalances);
    const buyerBalance = await balanceRepo.findOne({ where: { player_id: buyerId } });
    if (!buyerBalance) throw new Error('Solde introuvable');
    if (buyerBalance.infinite_light < price) {
      throw new Error(`Fonds insuffisants (${buyerBalance.infinite_light} / ${price} requis)`);
    }

    // Debit buyer
    buyerBalance.infinite_light -= price;
    await balanceRepo.save(buyerBalance);

    // Credit seller (if not Municipalite NPC, credit their balance)
    const sellerPlayer = await AppDataSource.getRepository(Player).findOne({
      where: { id: business.player_id },
    });
    if (sellerPlayer && !sellerPlayer.is_npc) {
      const sellerBalance = await balanceRepo.findOne({ where: { player_id: business.player_id } });
      if (sellerBalance) {
        sellerBalance.infinite_light += Math.round(price * 0.95); // 5% transaction fee
        await balanceRepo.save(sellerBalance);
      }
    }

    // Transfer ownership
    const previousOwner = business.player_id;
    business.player_id = buyerId;
    await businessRepo().save(business);

    // Log transaction
    await TransactionService.log({
      player_id: buyerId,
      category: 'commerce',
      type: 'out',
      amount: price,
      currency: 'infinite_light',
      description: `Achat business: ${business.name}`,
    });

    return business;
  }

  /**
   * Sell a business back (to Municipalite or marketplace).
   * Credits sale_value (70% of purchase_price) to the seller.
   */
  static async sellBusiness(businessId: string, sellerId: string): Promise<Business> {
    const business = await businessRepo().findOne({ where: { id: businessId } });
    if (!business) throw new Error('Business introuvable');
    if (business.player_id !== sellerId) throw new Error('Ce business ne vous appartient pas');

    const saleValue = business.sale_value || Math.round(business.purchase_price * 0.7);

    // Credit seller
    const balanceRepo = AppDataSource.getRepository(PlayerBalances);
    const sellerBalance = await balanceRepo.findOne({ where: { player_id: sellerId } });
    if (!sellerBalance) throw new Error('Solde introuvable');
    sellerBalance.infinite_light += saleValue;
    await balanceRepo.save(sellerBalance);

    // Transfer back to Municipalite
    const municipalite = await AppDataSource.getRepository(Player).findOne({
      where: { is_npc: true, npc_role: 'municipalite' as any },
    });
    if (municipalite) {
      business.player_id = municipalite.id;
    }
    await businessRepo().save(business);

    await TransactionService.log({
      player_id: sellerId,
      category: 'commerce',
      type: 'in',
      amount: saleValue,
      currency: 'infinite_light',
      description: `Vente business: ${business.name}`,
    });

    return business;
  }

  static async deleteBusiness(id: string, playerId: string) {
    const business = await businessRepo().findOne({ where: { id } });
    if (!business) return null;
    if (business.player_id !== playerId) return null;
    await businessRepo().remove(business);
    return true;
  }

  // ── Mettre en vente (Phase 15 Iter 7.2, 19-04-2026) ─────────
  // Toggle is_for_sale + sale_price_light sur business/residence/warehouse
  // sans transférer la propriété. L'acquéreur devra utiliser 'buy' / 'takeover'.

  static async listForSale(
    poiType: 'business' | 'residence' | 'warehouse',
    id: string,
    sellerId: string,
    priceLight: number,
  ): Promise<any> {
    if (!priceLight || priceLight < 100) throw new Error('Prix minimum 100 ∞');
    const row: any = poiType === 'business'
      ? await businessRepo().findOne({ where: { id } })
      : poiType === 'residence'
        ? await residenceRepo().findOne({ where: { id } })
        : await warehouseRepo().findOne({ where: { id } });
    if (!row) throw new Error('POI introuvable');
    if (row.player_id !== sellerId) throw new Error('Ce POI ne vous appartient pas');
    row.is_for_sale = true;
    row.sale_price_light = priceLight;
    if (poiType === 'business') await businessRepo().save(row);
    else if (poiType === 'residence') await residenceRepo().save(row);
    else await warehouseRepo().save(row);
    return { id, is_for_sale: true, sale_price_light: priceLight };
  }

  static async unlist(
    poiType: 'business' | 'residence' | 'warehouse',
    id: string,
    sellerId: string,
  ): Promise<any> {
    const row: any = poiType === 'business'
      ? await businessRepo().findOne({ where: { id } })
      : poiType === 'residence'
        ? await residenceRepo().findOne({ where: { id } })
        : await warehouseRepo().findOne({ where: { id } });
    if (!row) throw new Error('POI introuvable');
    if (row.player_id !== sellerId) throw new Error('Ce POI ne vous appartient pas');
    row.is_for_sale = false;
    row.sale_price_light = null;
    if (poiType === 'business') await businessRepo().save(row);
    else if (poiType === 'residence') await residenceRepo().save(row);
    else await warehouseRepo().save(row);
    return { id, is_for_sale: false };
  }

  // ── Residences ─────────────────────────────────────────────

  static async getPlayerResidences(playerId: string) {
    return residenceRepo().find({
      where: { player_id: playerId },
      order: { created_at: 'DESC' },
    });
  }

  static async getResidenceById(id: string, playerId: string) {
    const residence = await residenceRepo().findOne({ where: { id } });
    if (!residence) return null;
    if (residence.player_id !== playerId) return null;
    return residence;
  }

  static async createResidence(playerId: string, data: Partial<Residence>) {
    const residence = residenceRepo().create({
      ...data,
      player_id: playerId,
    });
    return residenceRepo().save(residence);
  }

  static async updateResidence(id: string, playerId: string, data: Partial<Residence>) {
    const residence = await residenceRepo().findOne({ where: { id } });
    if (!residence) return null;
    if (residence.player_id !== playerId) return null;

    // Planque active enforcement: only ONE residence can be active at a time
    if (data.is_planque_active === true && !residence.is_planque_active) {
      await residenceRepo().update(
        { player_id: playerId, is_planque_active: true },
        { is_planque_active: false },
      );
    }

    Object.assign(residence, data);
    return residenceRepo().save(residence);
  }

  /** Set a specific residence as the active planque (deactivates all others) */
  static async setPlanqueActive(residenceId: string, playerId: string) {
    const residence = await residenceRepo().findOne({ where: { id: residenceId } });
    if (!residence) throw new Error('Résidence introuvable');
    if (residence.player_id !== playerId) throw new Error('Non autorisé');

    // Deactivate all other planques for this player
    await residenceRepo().update(
      { player_id: playerId, is_planque_active: true },
      { is_planque_active: false },
    );

    // Activate the chosen one
    residence.is_planque_active = true;
    return residenceRepo().save(residence);
  }

  static async deleteResidence(id: string, playerId: string) {
    const residence = await residenceRepo().findOne({ where: { id } });
    if (!residence) return null;
    if (residence.player_id !== playerId) return null;
    await residenceRepo().remove(residence);
    return true;
  }

  // ── Vehicles ───────────────────────────────────────────────

  static async getPlayerVehicles(playerId: string) {
    return vehicleRepo().find({
      where: { player_id: playerId },
      order: { created_at: 'DESC' },
    });
  }

  static async getVehicleById(id: string, playerId: string) {
    const vehicle = await vehicleRepo().findOne({ where: { id } });
    if (!vehicle) return null;
    if (vehicle.player_id !== playerId) return null;
    return vehicle;
  }

  static async createVehicle(playerId: string, data: Partial<Vehicle>) {
    const vehicle = vehicleRepo().create({
      ...data,
      player_id: playerId,
    });
    return vehicleRepo().save(vehicle);
  }

  static async updateVehicle(id: string, playerId: string, data: Partial<Vehicle>) {
    const vehicle = await vehicleRepo().findOne({ where: { id } });
    if (!vehicle) return null;
    if (vehicle.player_id !== playerId) return null;
    Object.assign(vehicle, data);
    return vehicleRepo().save(vehicle);
  }

  static async deleteVehicle(id: string, playerId: string) {
    const vehicle = await vehicleRepo().findOne({ where: { id } });
    if (!vehicle) return null;
    if (vehicle.player_id !== playerId) return null;
    await vehicleRepo().remove(vehicle);
    return true;
  }

  // ── Warehouses ─────────────────────────────────────────────

  static async getPlayerWarehouses(playerId: string) {
    return warehouseRepo().find({
      where: { player_id: playerId },
      order: { created_at: 'DESC' },
    });
  }

  static async getWarehouseById(id: string, playerId: string) {
    const warehouse = await warehouseRepo().findOne({ where: { id } });
    if (!warehouse) return null;
    if (warehouse.player_id !== playerId) return null;
    return warehouse;
  }

  static async createWarehouse(playerId: string, data: Partial<Warehouse>) {
    const warehouse = warehouseRepo().create({
      ...data,
      player_id: playerId,
    });
    return warehouseRepo().save(warehouse);
  }

  static async updateWarehouse(id: string, playerId: string, data: Partial<Warehouse>) {
    const warehouse = await warehouseRepo().findOne({ where: { id } });
    if (!warehouse) return null;
    if (warehouse.player_id !== playerId) return null;
    Object.assign(warehouse, data);
    return warehouseRepo().save(warehouse);
  }

  static async deleteWarehouse(id: string, playerId: string) {
    const warehouse = await warehouseRepo().findOne({ where: { id } });
    if (!warehouse) return null;
    if (warehouse.player_id !== playerId) return null;
    await warehouseRepo().remove(warehouse);
    return true;
  }

  // ══════════════════════════════════════════════════════════════════
  // ITEM TRANSFERS (audit 15-04-2026, Phase 5)
  // ══════════════════════════════════════════════════════════════════
  //
  // Transfert d'items entre proprietes du joueur (residence, business,
  // warehouse, vehicle, on_person). La capacite est calculee DYNAMIQUEMENT
  // via SUM(player_inventory.weight_grams) plutot que de se fier aux champs
  // denormalises (current_stock_kg, current_fill) qui peuvent deriver.
  //
  // Toute operation est encapsulee dans une transaction SQL pour garantir
  // l'atomicite source-destination.

  /** Calcule la storage_condition attendue selon le type de destination */
  private static storageConditionFor(locationType: StorageLocationType): StorageCondition {
    switch (locationType) {
      case 'residence': return 'stashed';
      case 'business':  return 'stored';
      case 'warehouse': return 'stored';
      case 'vehicle':   return 'vehicle';
      case 'player':    return 'on_person';
      default: throw new Error(`Location type inconnu: ${locationType}`);
    }
  }

  /**
   * Verifie que le joueur est proprietaire de l'entite a la localisation.
   * Pour 'player' (on_person), on verifie que locationId === playerId.
   */
  private static async verifyOwnership(
    playerId: string,
    locationType: StorageLocationType,
    locationId: string,
  ): Promise<boolean> {
    if (locationType === 'player') return locationId === playerId;
    const repo =
      locationType === 'residence' ? residenceRepo()
      : locationType === 'business' ? businessRepo()
      : locationType === 'warehouse' ? warehouseRepo()
      : locationType === 'vehicle' ? vehicleRepo()
      : null;
    if (!repo) return false;
    const entity = await repo.findOne({ where: { id: locationId } as any });
    return !!entity && (entity as any).player_id === playerId;
  }

  /**
   * Calcule dynamiquement le poids reel stocke a une localisation
   * en sommant les weight_grams * quantity de l'inventaire.
   * Ignore volontairement les champs denormalises (current_stock_kg).
   */
  private static async computeFilledKg(
    locationType: StorageLocationType,
    locationId: string,
    playerId: string,
  ): Promise<{ filled_kg: number; item_count: number }> {
    const condition = PropertyService.storageConditionFor(locationType);

    if (locationType === 'player') {
      // on_person : somme des items du joueur sans storage_location_id
      const rows = await inventoryRepo()
        .createQueryBuilder('pi')
        .select('COALESCE(SUM(pi.weight_grams * pi.quantity), 0)', 'total_grams')
        .addSelect('COUNT(pi.id)', 'cnt')
        .where('pi.player_id = :pid', { pid: playerId })
        .andWhere('pi.storage_condition = :cond', { cond: condition })
        .getRawOne<{ total_grams: string; cnt: string }>();
      const grams = Number(rows?.total_grams || 0);
      return { filled_kg: grams / 1000, item_count: Number(rows?.cnt || 0) };
    }

    const rows = await inventoryRepo()
      .createQueryBuilder('pi')
      .select('COALESCE(SUM(pi.weight_grams * pi.quantity), 0)', 'total_grams')
      .addSelect('COUNT(pi.id)', 'cnt')
      .where('pi.storage_location_id = :loc', { loc: locationId })
      .andWhere('pi.storage_condition = :cond', { cond: condition })
      .getRawOne<{ total_grams: string; cnt: string }>();
    const grams = Number(rows?.total_grams || 0);
    return { filled_kg: grams / 1000, item_count: Number(rows?.cnt || 0) };
  }

  /**
   * Capacite max d'une localisation, lue depuis l'entite proprietaire.
   * - residence.storage_capacity
   * - business.storage_capacity_kg
   * - warehouse.capacity
   * - vehicle.storage_capacity
   * - player/on_person : 35 kg (cf. weight_malus dans mission.service.ts)
   */
  private static async computeMaxCapacityKg(
    locationType: StorageLocationType,
    locationId: string,
  ): Promise<number> {
    if (locationType === 'player') return ON_PERSON_MAX_KG;
    if (locationType === 'residence') {
      const r = await residenceRepo().findOne({ where: { id: locationId } });
      return r?.storage_capacity ?? 0;
    }
    if (locationType === 'business') {
      const b = await businessRepo().findOne({ where: { id: locationId } });
      return b?.storage_capacity_kg ?? 0;
    }
    if (locationType === 'warehouse') {
      const w = await warehouseRepo().findOne({ where: { id: locationId } });
      return w?.capacity ?? 0;
    }
    if (locationType === 'vehicle') {
      const v = await vehicleRepo().findOne({ where: { id: locationId } });
      return v?.storage_capacity ?? 0;
    }
    return 0;
  }

  /**
   * Retourne la capacite d'une localisation avec poids actuel dynamique.
   * Exposé via GET /api/property/capacity pour l'UI de transfert.
   */
  static async getCapacity(
    playerId: string,
    locationType: StorageLocationType,
    locationId: string,
  ): Promise<LocationCapacity> {
    const owned = await PropertyService.verifyOwnership(playerId, locationType, locationId);
    if (!owned) throw new Error('Localisation inconnue ou ne vous appartient pas');

    const capacity_kg = await PropertyService.computeMaxCapacityKg(locationType, locationId);
    const { filled_kg, item_count } = await PropertyService.computeFilledKg(locationType, locationId, playerId);
    const remaining_kg = Math.max(0, capacity_kg - filled_kg);

    return { location_type: locationType, location_id: locationId, capacity_kg, filled_kg, remaining_kg, item_count };
  }

  /**
   * Liste les items stockes a une localisation (via SUM dynamique).
   * Expose via GET /api/property/items.
   */
  static async listItemsAtLocation(
    playerId: string,
    locationType: StorageLocationType,
    locationId: string,
  ): Promise<PlayerInventory[]> {
    const owned = await PropertyService.verifyOwnership(playerId, locationType, locationId);
    if (!owned) throw new Error('Localisation inconnue ou ne vous appartient pas');

    const condition = PropertyService.storageConditionFor(locationType);

    if (locationType === 'player') {
      return inventoryRepo().find({
        where: { player_id: playerId, storage_condition: condition },
        order: { item_type: 'ASC', item_subtype: 'ASC' },
      });
    }

    return inventoryRepo().find({
      where: {
        storage_location_id: locationId,
        storage_condition: condition,
        player_id: playerId,
      },
      order: { item_type: 'ASC', item_subtype: 'ASC' },
    });
  }

  /**
   * Transfere une quantite d'items entre deux localisations appartenant au joueur.
   * Atomique (transaction SQL), recalcule la storage_condition selon la destination,
   * verifie la capacite dynamique et rejette si l'item est hypotheque (is_listed).
   */
  static async transferItem(
    playerId: string,
    params: TransferItemParams,
  ): Promise<{ success: boolean; message: string; source_remaining: number; destination_remaining: number }> {
    // Validation d'entree
    const qty = Math.trunc(Number(params.quantity) || 0);
    if (qty <= 0) throw new Error('Quantite invalide');
    if (params.source_location_type === params.destination_location_type
        && params.source_location_id === params.destination_location_id) {
      throw new Error('Source et destination identiques');
    }

    // Ownership source + destination (hors transaction — echec rapide)
    const [srcOwned, dstOwned] = await Promise.all([
      PropertyService.verifyOwnership(playerId, params.source_location_type, params.source_location_id),
      PropertyService.verifyOwnership(playerId, params.destination_location_type, params.destination_location_id),
    ]);
    if (!srcOwned) throw new Error('La localisation source ne vous appartient pas');
    if (!dstOwned) throw new Error('La localisation destination ne vous appartient pas');

    // Transaction atomique : lock item, verif capacite destination, update
    return AppDataSource.transaction(async (mgr: EntityManager) => {
      const invMgr = mgr.getRepository(PlayerInventory);

      // 1. Lock l'item via SELECT ... FOR UPDATE (empeche double-transfert)
      const item = await invMgr
        .createQueryBuilder('pi')
        .setLock('pessimistic_write')
        .where('pi.id = :id', { id: params.inventory_id })
        .getOne();

      if (!item) throw new Error('Item introuvable');
      if (item.player_id !== playerId) throw new Error('Cet item ne vous appartient pas');
      if (item.is_listed) throw new Error('Item hypotheque sur le marketplace, retirez l\'annonce d\'abord');

      // 2. Verifier que l'item est bien a la source declaree
      const expectedSrcCondition = PropertyService.storageConditionFor(params.source_location_type);
      if (item.storage_condition !== expectedSrcCondition) {
        throw new Error(`L'item n'est pas en etat "${expectedSrcCondition}" (actuel: ${item.storage_condition})`);
      }
      if (params.source_location_type === 'player') {
        if (item.storage_location_id !== null) {
          throw new Error('L\'item on_person ne devrait pas avoir de storage_location_id');
        }
      } else {
        if (item.storage_location_id !== params.source_location_id) {
          throw new Error('L\'item ne se trouve pas a la localisation source declaree');
        }
      }

      if (qty > item.quantity) {
        throw new Error(`Quantite demandee (${qty}) superieure au stock (${item.quantity})`);
      }

      // 3. Capacite destination (dynamique, via SUM)
      const destCapacity = await PropertyService.computeMaxCapacityKg(
        params.destination_location_type, params.destination_location_id,
      );
      const dstFilled = await PropertyService.computeFilledKg(
        params.destination_location_type, params.destination_location_id, playerId,
      );
      const transferKg = (Number(item.weight_grams) * qty) / 1000;
      const dstRemainingBefore = Math.max(0, destCapacity - dstFilled.filled_kg);
      if (transferKg > dstRemainingBefore) {
        throw new Error(
          `Capacite insuffisante a destination (${dstRemainingBefore.toFixed(2)}kg dispo, ${transferKg.toFixed(2)}kg requis)`,
        );
      }

      // 4. Execute le transfer
      const newCondition = PropertyService.storageConditionFor(params.destination_location_type);
      const newLocationId = params.destination_location_type === 'player' ? null : params.destination_location_id;

      if (qty >= item.quantity) {
        // Transfert total : update la row existante
        item.quantity = qty;
        item.storage_condition = newCondition;
        item.storage_location_id = newLocationId;
        await invMgr.save(item);
      } else {
        // Transfert partiel : diminue la row source, cree une nouvelle row destination
        item.quantity -= qty;
        await invMgr.save(item);

        const newItem = invMgr.create({
          player_id: playerId,
          item_type: item.item_type,
          item_subtype: item.item_subtype,
          quantity: qty,
          quality: item.quality,
          storage_condition: newCondition,
          storage_location_id: newLocationId,
          weight_grams: item.weight_grams,
          is_listed: false,
          listing_id: null,
          expires_at: item.expires_at,
        });
        await invMgr.save(newItem);
      }

      // 5. Pas de TransactionService.log ici : les transferts d'items n'impliquent
      //    aucun mouvement de balance, et TransactionService est typé pour 'in'/'out'
      //    monétaires. On pourra ajouter un ActivityLog Phase 11 si besoin d'audit.

      // 6. Retour capacites actualisees (approx — les vraies valeurs necessiteraient un re-query post-commit)
      return {
        success: true,
        message: `${qty}x ${item.item_subtype} transferes`,
        source_remaining: 0, // sera re-query cote caller si besoin
        destination_remaining: Math.max(0, dstRemainingBefore - transferKg),
      };
    });
  }
}

