import { AppDataSource } from '../config/database';
import { PlayerInventory } from '../models/PlayerInventory';
import { Vehicle } from '../models/Vehicle';
import { GangMember } from '../models/GangMember';
import { CartelMember } from '../models/CartelMember';
import { Gang } from '../models/Gang';
import { CartelTerritory } from '../models/CartelTerritory';

const inventoryRepo = () => AppDataSource.getRepository(PlayerInventory);
const vehicleRepo = () => AppDataSource.getRepository(Vehicle);
const gangMemberRepo = () => AppDataSource.getRepository(GangMember);
const cartelMemberRepo = () => AppDataSource.getRepository(CartelMember);
const gangRepo = () => AppDataSource.getRepository(Gang);
const territoryRepo = () => AppDataSource.getRepository(CartelTerritory);

/**
 * Phase 15 (20-04-2026) — stationnement autour du POI Territoire.
 *
 * Consigne user : « Les véhicules alloués au gang sont garés autour du POIS
 * Point de Territoire (dans un rayon de 50 mètres) ». Si le véhicule a un
 * garage/résidence attaché (assigned_residence_id non-null), il reste
 * invisible sur la carte (dans le garage) ; il apparaîtra temporairement
 * au départ d'une mission puis retournera au garage à la fin.
 *
 * Rayon ~50 m → offset lat/lng d'environ 0.00045 degré (1 deg ≈ 111 km).
 */
const PARK_RADIUS_DEG = 0.00045;

function randomOffsetInRadius(): { dLat: number; dLng: number } {
  const r = Math.sqrt(Math.random()) * PARK_RADIUS_DEG;
  const theta = Math.random() * 2 * Math.PI;
  return { dLat: r * Math.cos(theta), dLng: r * Math.sin(theta) };
}

/**
 * Allocations virtuelles (Phase 15, 19-04-2026) — Q-D utilisateur.
 *
 * L'item ou le véhicule reste physiquement chez le joueur. On marque juste
 * assigned_to_gang_id ou assigned_to_cartel_id pour indiquer qu'il est mis
 * à disposition du gang/cartel. Les ordres de mission peuvent alors l'équiper
 * sur les gangsters. Au désassignement (UI ou fin de mission), la colonne
 * repasse à NULL — pas de déplacement physique.
 *
 * Règles :
 *  - Un item/véhicule ne peut être alloué qu'à UN seul gang OU cartel à la fois.
 *  - Le player doit être membre du gang/cartel visé.
 *  - Un item en cours de listing marketplace (is_listed=true) ne peut pas être
 *    alloué.
 */
export class AllocationService {
  // ──────────────────────────────────────────────────────────
  // INVENTORY (armes, gilets, drogues, items divers)
  // ──────────────────────────────────────────────────────────

  /**
   * Phase 15 (20-04-2026) — capture le lieu d'origine d'un item avant de
   * l'allouer à un gang/cartel. Consigne user L672 : « il se destock
   * automatiquement d'un lieu de stockage actuel de notre parc pour aller
   * au gang donc si on le desassigne du gang il retourne au lieu de
   * stockage précedent ».
   *
   * Map storage_condition → previous_location_type :
   *   - 'stored' (résidence/business/warehouse) → dérive via storage_location_id
   *     qu'on checke contre chaque repo. Fallback : 'player' (sur soi).
   *   - 'vehicle' → 'vehicle'
   *   - 'on_person' | 'stashed' | 'listed' → 'player'
   */
  private static capturePreviousLocation(item: PlayerInventory): { previous_location_type: string; previous_location_id: string } {
    if (item.storage_condition === 'vehicle' && item.storage_location_id) {
      return { previous_location_type: 'vehicle', previous_location_id: item.storage_location_id };
    }
    if (item.storage_condition === 'stored' && item.storage_location_id) {
      // On ne tranche pas residence/business/warehouse ici — l'ID seul suffit,
      // au restore on checke le bon repo. Par défaut on marque 'residence' et
      // au restore, un fallback traite les autres cas.
      return { previous_location_type: 'residence', previous_location_id: item.storage_location_id };
    }
    return { previous_location_type: 'player', previous_location_id: item.player_id };
  }

  static async allocateInventoryToGang(playerId: string, inventoryId: string, gangId: string): Promise<void> {
    const item = await inventoryRepo().findOne({ where: { id: inventoryId, player_id: playerId } });
    if (!item) throw new Error('Item introuvable dans votre inventaire');
    if (item.is_listed) throw new Error('Item en annonce marketplace, retirez-le avant');
    if (item.assigned_to_cartel_id) throw new Error('Item déjà alloué à un cartel');
    if (item.assigned_to_gang_id && item.assigned_to_gang_id !== gangId) {
      throw new Error('Item déjà alloué à un autre gang');
    }

    const member = await gangMemberRepo().findOne({ where: { gang_id: gangId, player_id: playerId } });
    if (!member) throw new Error('Vous n\'êtes pas membre de ce gang');

    // Capture origine seulement si pas déjà allouée (pas d'overwrite si ré-assignement)
    const patch: any = { assigned_to_gang_id: gangId };
    if (!item.previous_location_type) {
      const cap = AllocationService.capturePreviousLocation(item);
      patch.previous_location_type = cap.previous_location_type;
      patch.previous_location_id = cap.previous_location_id;
    }

    await inventoryRepo().update(inventoryId, patch);
  }

  static async deallocateInventoryFromGang(playerId: string, inventoryId: string): Promise<void> {
    const item = await inventoryRepo().findOne({ where: { id: inventoryId, player_id: playerId } });
    if (!item) throw new Error('Item introuvable');
    // Phase 15 (20-04-2026) — restauration au lieu d'origine si disponible
    const restore = AllocationService.buildRestorePatch(item);
    await inventoryRepo().update(inventoryId, { assigned_to_gang_id: null, ...restore });
  }

  static async allocateInventoryToCartel(playerId: string, inventoryId: string, cartelId: string): Promise<void> {
    const item = await inventoryRepo().findOne({ where: { id: inventoryId, player_id: playerId } });
    if (!item) throw new Error('Item introuvable dans votre inventaire');
    if (item.is_listed) throw new Error('Item en annonce marketplace');
    if (item.assigned_to_gang_id) throw new Error('Item déjà alloué à un gang');
    if (item.assigned_to_cartel_id && item.assigned_to_cartel_id !== cartelId) {
      throw new Error('Item déjà alloué à un autre cartel');
    }

    const gm = await gangMemberRepo().findOne({ where: { player_id: playerId } });
    if (!gm) throw new Error('Vous devez être dans un gang');
    const cm = await cartelMemberRepo().findOne({ where: { gang_id: gm.gang_id, cartel_id: cartelId, status: 'active' } });
    if (!cm) throw new Error('Votre gang n\'est pas dans ce cartel');

    const patch: any = { assigned_to_cartel_id: cartelId };
    if (!item.previous_location_type) {
      const cap = AllocationService.capturePreviousLocation(item);
      patch.previous_location_type = cap.previous_location_type;
      patch.previous_location_id = cap.previous_location_id;
    }
    await inventoryRepo().update(inventoryId, patch);
  }

  static async deallocateInventoryFromCartel(playerId: string, inventoryId: string): Promise<void> {
    const item = await inventoryRepo().findOne({ where: { id: inventoryId, player_id: playerId } });
    if (!item) {
      await inventoryRepo().update({ id: inventoryId, player_id: playerId }, { assigned_to_cartel_id: null });
      return;
    }
    const restore = AllocationService.buildRestorePatch(item);
    await inventoryRepo().update(inventoryId, { assigned_to_cartel_id: null, ...restore });
  }

  /**
   * Restaure storage_condition + storage_location_id depuis previous_location.
   * Fallback : si lieu disparu (bâtiment vendu…), retombe sur 'on_person'/player.
   * Nettoie les previous_* pour signaler qu'ils ont été consommés.
   */
  private static buildRestorePatch(item: PlayerInventory): any {
    if (!item.previous_location_type || !item.previous_location_id) return {};
    let storage_condition: string | null = null;
    let storage_location_id: string | null = item.previous_location_id;
    switch (item.previous_location_type) {
      case 'vehicle':
        storage_condition = 'vehicle'; break;
      case 'residence':
      case 'business':
      case 'warehouse':
        storage_condition = 'stored'; break;
      case 'player':
      default:
        storage_condition = 'on_person';
        storage_location_id = null;
        break;
    }
    return {
      storage_condition,
      storage_location_id,
      previous_location_type: null,
      previous_location_id: null,
    };
  }

  // ──────────────────────────────────────────────────────────
  // VEHICLES
  // ──────────────────────────────────────────────────────────

  /** Capture le lieu d'origine d'un véhicule (garage/résidence) avant allocation gang/cartel. */
  private static captureVehiclePreviousLocation(v: any): { previous_location_type: string; previous_location_id: string } {
    if (v.assigned_residence_id) {
      return { previous_location_type: 'residence', previous_location_id: v.assigned_residence_id };
    }
    return { previous_location_type: 'player', previous_location_id: v.player_id };
  }

  /** Restaure l'assigned_residence_id du véhicule depuis previous_location (ou null si player). */
  private static buildVehicleRestorePatch(v: any): any {
    if (!v.previous_location_type || !v.previous_location_id) return {};
    if (v.previous_location_type === 'residence') {
      return {
        assigned_residence_id: v.previous_location_id,
        previous_location_type: null,
        previous_location_id: null,
      };
    }
    return {
      assigned_residence_id: null,
      previous_location_type: null,
      previous_location_id: null,
    };
  }

  /**
   * Phase 15 (20-04-2026) — stationnement auto autour du POI Territoire
   * gang (rayon 50m). Si le véhicule a un garage (assigned_residence_id),
   * on ne bouge pas sa position : il reste "dans" le garage invisible.
   */
  private static async parkVehicleNearGangTerritory(
    vehicleId: string, gangId: string, hasGarage: boolean,
  ): Promise<void> {
    if (hasGarage) return;
    const gang = await gangRepo().findOneBy({ id: gangId });
    if (!gang || gang.origin_lat == null || gang.origin_lng == null) return;
    const { dLat, dLng } = randomOffsetInRadius();
    await vehicleRepo().update(vehicleId, {
      current_lat: Number(gang.origin_lat) + dLat,
      current_lon: Number(gang.origin_lng) + dLng,
      in_use: false,
      driven_by: null,
    });
  }

  private static async parkVehicleNearCartelTerritory(
    vehicleId: string, cartelId: string, hasGarage: boolean,
  ): Promise<void> {
    if (hasGarage) return;
    const origin = await territoryRepo().findOne({
      where: { cartel_id: cartelId, is_origin: true, lost_at: null as any },
    });
    if (!origin) return;
    const { dLat, dLng } = randomOffsetInRadius();
    await vehicleRepo().update(vehicleId, {
      current_lat: Number(origin.lat) + dLat,
      current_lon: Number(origin.lng) + dLng,
      in_use: false,
      driven_by: null,
    });
  }

  static async allocateVehicleToGang(playerId: string, vehicleId: string, gangId: string): Promise<void> {
    const v = await vehicleRepo().findOne({ where: { id: vehicleId, player_id: playerId } });
    if (!v) throw new Error('Véhicule introuvable');
    if (v.assigned_to_cartel_id) throw new Error('Véhicule déjà alloué à un cartel');
    if (v.assigned_to_gang_id && v.assigned_to_gang_id !== gangId) {
      throw new Error('Véhicule déjà alloué à un autre gang');
    }
    const member = await gangMemberRepo().findOne({ where: { gang_id: gangId, player_id: playerId } });
    if (!member) throw new Error('Pas membre du gang');

    const patch: any = { assigned_to_gang_id: gangId };
    if (!v.previous_location_type) {
      const cap = AllocationService.captureVehiclePreviousLocation(v);
      patch.previous_location_type = cap.previous_location_type;
      patch.previous_location_id = cap.previous_location_id;
    }
    await vehicleRepo().update(vehicleId, patch);

    // Phase 15 (20-04-2026) — stationnement auto à 50m du Point de Territoire
    // gang, sauf si le véhicule a un garage (assigned_residence_id) auquel cas
    // il reste dans le garage et "apparaîtra" au départ d'une mission.
    await AllocationService.parkVehicleNearGangTerritory(vehicleId, gangId, !!v.assigned_residence_id);
  }

  static async deallocateVehicleFromGang(playerId: string, vehicleId: string): Promise<void> {
    const v = await vehicleRepo().findOne({ where: { id: vehicleId, player_id: playerId } });
    if (!v) {
      await vehicleRepo().update({ id: vehicleId, player_id: playerId }, { assigned_to_gang_id: null });
      return;
    }
    const restore = AllocationService.buildVehicleRestorePatch(v);
    await vehicleRepo().update(vehicleId, { assigned_to_gang_id: null, ...restore });
  }

  static async allocateVehicleToCartel(playerId: string, vehicleId: string, cartelId: string): Promise<void> {
    const v = await vehicleRepo().findOne({ where: { id: vehicleId, player_id: playerId } });
    if (!v) throw new Error('Véhicule introuvable');
    if (v.assigned_to_gang_id) throw new Error('Véhicule déjà alloué à un gang');
    const gm = await gangMemberRepo().findOne({ where: { player_id: playerId } });
    if (!gm) throw new Error('Pas dans un gang');
    const cm = await cartelMemberRepo().findOne({ where: { gang_id: gm.gang_id, cartel_id: cartelId, status: 'active' } });
    if (!cm) throw new Error('Pas dans ce cartel');

    const patch: any = { assigned_to_cartel_id: cartelId };
    if (!v.previous_location_type) {
      const cap = AllocationService.captureVehiclePreviousLocation(v);
      patch.previous_location_type = cap.previous_location_type;
      patch.previous_location_id = cap.previous_location_id;
    }
    await vehicleRepo().update(vehicleId, patch);

    // Phase 15 (20-04-2026) — stationnement auto à 50m du territoire d'origine
    await AllocationService.parkVehicleNearCartelTerritory(vehicleId, cartelId, !!v.assigned_residence_id);
  }

  static async deallocateVehicleFromCartel(playerId: string, vehicleId: string): Promise<void> {
    const v = await vehicleRepo().findOne({ where: { id: vehicleId, player_id: playerId } });
    if (!v) {
      await vehicleRepo().update({ id: vehicleId, player_id: playerId }, { assigned_to_cartel_id: null });
      return;
    }
    const restore = AllocationService.buildVehicleRestorePatch(v);
    await vehicleRepo().update(vehicleId, { assigned_to_cartel_id: null, ...restore });
  }

  // ──────────────────────────────────────────────────────────
  // QUERIES (pour UI tableaux gauche/droite)
  // ──────────────────────────────────────────────────────────

  /** Items du joueur qui NE sont PAS alloués au gang/cartel (stock personnel). */
  static async getPlayerPersonalInventory(playerId: string): Promise<PlayerInventory[]> {
    return inventoryRepo().find({
      where: { player_id: playerId, assigned_to_gang_id: null as any, assigned_to_cartel_id: null as any, is_listed: false },
      order: { created_at: 'DESC' },
    });
  }

  /** Items alloués par TOUS les membres d'un gang. */
  static async getGangAllocatedInventory(gangId: string): Promise<PlayerInventory[]> {
    return inventoryRepo().find({
      where: { assigned_to_gang_id: gangId },
      order: { created_at: 'DESC' },
    });
  }

  static async getCartelAllocatedInventory(cartelId: string): Promise<PlayerInventory[]> {
    return inventoryRepo().find({
      where: { assigned_to_cartel_id: cartelId },
      order: { created_at: 'DESC' },
    });
  }

  /** Véhicules non alloués (stock perso). */
  static async getPlayerPersonalVehicles(playerId: string): Promise<Vehicle[]> {
    return vehicleRepo().find({
      where: { player_id: playerId, assigned_to_gang_id: null as any, assigned_to_cartel_id: null as any },
      order: { created_at: 'DESC' },
    });
  }

  static async getGangAllocatedVehicles(gangId: string): Promise<Vehicle[]> {
    return vehicleRepo().find({ where: { assigned_to_gang_id: gangId }, order: { created_at: 'DESC' } });
  }

  static async getCartelAllocatedVehicles(cartelId: string): Promise<Vehicle[]> {
    return vehicleRepo().find({ where: { assigned_to_cartel_id: cartelId }, order: { created_at: 'DESC' } });
  }
}
