import { AppDataSource } from '../config/database';
import { Hideout, HideoutStock, HideoutVehicle } from '../models/Hideout';
import { PlayerInventory } from '../models/PlayerInventory';
import { Vehicle } from '../models/Vehicle';

const hideoutRepo = () => AppDataSource.getRepository(Hideout);
const stockRepo = () => AppDataSource.getRepository(HideoutStock);
const vehicleSlotRepo = () => AppDataSource.getRepository(HideoutVehicle);
const inventoryRepo = () => AppDataSource.getRepository(PlayerInventory);
const vehicleRepo = () => AppDataSource.getRepository(Vehicle);

/**
 * Planques : invisibles aux ennemis (jamais affichées sur la carte côté adverse).
 * Générées 1 par km² autour d'un Point de Territoire.
 * Contenu : 200 kg items + 3 véhicules parkés. Survit aux takeovers/saisies.
 */
export class HideoutService {
  static readonly DEFAULT_CAPACITY_G = 200000;
  static readonly DEFAULT_VEHICLE_SLOTS = 3;

  static async create(
    ownerType: 'player' | 'gang' | 'cartel',
    ownerId: string,
    lat: number, lng: number,
    parentType?: 'player' | 'cartel',
    parentId?: string,
    name?: string,
  ): Promise<Hideout> {
    const h = hideoutRepo().create({
      owner_type: ownerType,
      owner_id: ownerId,
      lat, lng,
      name: name || null,
      storage_capacity_g: HideoutService.DEFAULT_CAPACITY_G,
      vehicle_slots: HideoutService.DEFAULT_VEHICLE_SLOTS,
      parent_territory_type: parentType || null,
      parent_territory_id: parentId || null,
      is_active: true,
    });
    return hideoutRepo().save(h);
  }

  /** Génère automatiquement des planques autour d'un Point de Territoire (1 par km²). */
  static async autoGenerateForTerritory(
    ownerType: 'player' | 'cartel',
    ownerId: string,
    centerLat: number, centerLng: number,
    radiusKm: number,
    parentType: 'player' | 'cartel',
    parentId: string,
  ): Promise<{ created: number }> {
    const existing = await hideoutRepo().count({
      where: { owner_type: ownerType, owner_id: ownerId, is_active: true },
    });
    // On vise 1 planque par km², cap à (surface ≈ π r²) planques existantes max
    const targetCount = Math.max(1, Math.floor(Math.PI * radiusKm * radiusKm));
    const toCreate = Math.max(0, targetCount - existing);
    let created = 0;
    for (let i = 0; i < toCreate; i++) {
      const r = Math.random() * (radiusKm * 1000);
      const theta = Math.random() * 2 * Math.PI;
      const dLat = (r * Math.cos(theta)) / 111000;
      const dLng = (r * Math.sin(theta)) / (111000 * Math.cos(centerLat * Math.PI / 180));
      await HideoutService.create(ownerType, ownerId, centerLat + dLat, centerLng + dLng, parentType, parentId);
      created++;
    }
    return { created };
  }

  static async listForOwner(ownerType: 'player' | 'gang' | 'cartel', ownerId: string): Promise<Hideout[]> {
    return hideoutRepo().find({
      where: { owner_type: ownerType, owner_id: ownerId, is_active: true },
      order: { created_at: 'ASC' },
    });
  }

  static async depositItem(
    hideoutId: string, playerId: string,
    itemType: string, itemSubtype: string | null,
    quantity: number, quality = 50, weightPerUnit_g = 100,
  ): Promise<HideoutStock> {
    const h = await hideoutRepo().findOneBy({ id: hideoutId, is_active: true });
    if (!h) throw new Error('Planque introuvable');
    const totalWeight = quantity * weightPerUnit_g;
    if (h.storage_used_g + totalWeight > h.storage_capacity_g) {
      throw new Error('Capacité planque dépassée');
    }
    const entry = stockRepo().create({
      hideout_id: hideoutId,
      item_type: itemType,
      item_subtype: itemSubtype,
      quantity,
      quality,
      weight_g: totalWeight,
      deposited_by: playerId,
    });
    const saved = await stockRepo().save(entry);
    await hideoutRepo().update(hideoutId, {
      storage_used_g: h.storage_used_g + totalWeight,
    });
    return saved;
  }

  static async withdrawStock(hideoutId: string, stockId: string, quantity?: number): Promise<HideoutStock> {
    const s = await stockRepo().findOneBy({ id: stockId, hideout_id: hideoutId });
    if (!s) throw new Error('Stock introuvable');
    const qty = Math.min(quantity ?? s.quantity, s.quantity);
    const weightDelta = Math.floor((qty / s.quantity) * s.weight_g);
    if (qty >= s.quantity) {
      await stockRepo().delete(s.id);
    } else {
      s.quantity -= qty;
      s.weight_g -= weightDelta;
      await stockRepo().save(s);
    }
    await hideoutRepo().createQueryBuilder().update()
      .set({ storage_used_g: () => `GREATEST(0, storage_used_g - ${weightDelta})` })
      .where('id = :id', { id: hideoutId })
      .execute();
    return s;
  }

  static async parkVehicle(hideoutId: string, vehicleId: string, playerId: string): Promise<HideoutVehicle> {
    const h = await hideoutRepo().findOneBy({ id: hideoutId, is_active: true });
    if (!h) throw new Error('Planque introuvable');
    const parked = await vehicleSlotRepo().count({ where: { hideout_id: hideoutId } });
    if (parked >= h.vehicle_slots) throw new Error('Tous les emplacements sont pris');
    // Vérifier unique
    const existing = await vehicleSlotRepo().findOne({ where: { vehicle_id: vehicleId } });
    if (existing) throw new Error('Véhicule déjà parqué dans une planque');
    return vehicleSlotRepo().save(vehicleSlotRepo().create({
      hideout_id: hideoutId, vehicle_id: vehicleId, parked_by: playerId,
    }));
  }

  static async unparkVehicle(hideoutId: string, vehicleId: string): Promise<void> {
    await vehicleSlotRepo().delete({ hideout_id: hideoutId, vehicle_id: vehicleId });
  }
}
