import { AppDataSource } from '../config/database';
import { LessThanOrEqual, In, IsNull } from 'typeorm';
import { GarageRental } from '../models/GarageRental';
import { Vehicle } from '../models/Vehicle';
import { Business } from '../models/Business';
import { PlayerBalances } from '../models/PlayerBalances';
import { TransactionService } from './transaction.service';
import { NotificationService } from './notification.service';
import { haversineDistance } from '../constants/travel-speeds';

const rentalRepo = () => AppDataSource.getRepository(GarageRental);
const vehicleRepo = () => AppDataSource.getRepository(Vehicle);
const businessRepo = () => AppDataSource.getRepository(Business);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);

/**
 * Phase 15 v2 (2026-04-22) — Garage storage.
 *
 * Consigne user : nouveau business_type 'garage_storage', prix 5..35
 * ∞-lumière par jour. Loyer facturé quotidiennement via CRON. Si le
 * joueur n'a plus les fonds, le contrat passe en `defaulted` et le
 * véhicule est retourné à l'ancienne résidence (ou hideout) si possible,
 * sinon il reste au garage mais avec rentrée au contact manquée.
 */
export class GarageRentalService {
  static readonly MIN_DAILY = 5;
  static readonly MAX_DAILY = 35;

  static async startRental(
    playerId: string,
    params: {
      business_id: string;
      vehicle_id: string;
      daily_rent_light: number;
    },
  ): Promise<GarageRental> {
    const daily = Math.max(
      GarageRentalService.MIN_DAILY,
      Math.min(GarageRentalService.MAX_DAILY, Math.floor(Number(params.daily_rent_light))),
    );

    const business = await businessRepo().findOne({ where: { id: params.business_id } });
    if (!business) throw new Error('Business introuvable');
    if (business.type !== 'garage_storage') {
      throw new Error('Ce business n\'est pas un garage de stockage');
    }

    const vehicle = await vehicleRepo().findOne({ where: { id: params.vehicle_id } });
    if (!vehicle) throw new Error('Véhicule introuvable');
    if (vehicle.player_id !== playerId) {
      throw new Error('Vous n\'êtes pas propriétaire de ce véhicule');
    }
    if (vehicle.in_use) throw new Error('Véhicule en usage — impossible de le stocker');

    // 1 seul contrat actif par véhicule
    const existing = await rentalRepo().findOne({
      where: { vehicle_id: params.vehicle_id, status: 'active' },
    });
    if (existing) throw new Error('Ce véhicule est déjà en location dans un garage');

    const now = new Date();
    const rental = rentalRepo().create({
      business_id: params.business_id,
      renter_player_id: playerId,
      vehicle_id: params.vehicle_id,
      daily_rent_light: daily,
      started_at: now,
      ends_at: null,
      last_rent_charged_at: null,
      status: 'active',
    });
    const saved = await rentalRepo().save(rental);

    // Déplace le véhicule physiquement au garage (location)
    if (business.location_lat != null && business.location_lon != null) {
      vehicle.current_lat = Number(business.location_lat);
      vehicle.current_lon = Number(business.location_lon);
    }
    vehicle.previous_location_type = 'business';
    vehicle.previous_location_id = params.business_id;
    await vehicleRepo().save(vehicle);

    return saved;
  }

  static async endRental(playerId: string, rentalId: string): Promise<GarageRental> {
    const rental = await rentalRepo().findOne({ where: { id: rentalId } });
    if (!rental) throw new Error('Location introuvable');
    if (rental.renter_player_id !== playerId) throw new Error('Vous n\'êtes pas le locataire');
    if (rental.status !== 'active') throw new Error('Location déjà terminée');

    rental.status = 'ended';
    rental.ends_at = new Date();
    await rentalRepo().save(rental);
    return rental;
  }

  /**
   * CRON quotidien : débite le loyer pour chaque contrat actif. Si les fonds
   * manquent → status='defaulted' + notif au joueur.
   */
  static async chargeDailyRents(): Promise<{ charged: number; defaulted: number }> {
    const now = new Date();
    const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);

    // Contrats qui n'ont pas été facturés depuis >= 24h (ou jamais)
    const due = await rentalRepo()
      .createQueryBuilder('r')
      .where('r.status = :status', { status: 'active' })
      .andWhere('(r.last_rent_charged_at IS NULL OR r.last_rent_charged_at <= :oneDayAgo)', { oneDayAgo })
      .getMany();

    let charged = 0;
    let defaulted = 0;

    for (const r of due) {
      const balance = await balancesRepo().findOneBy({ player_id: r.renter_player_id });
      if (!balance || Number(balance.infinite_light) < r.daily_rent_light) {
        r.status = 'defaulted';
        r.ends_at = now;
        await rentalRepo().save(r);
        await NotificationService.create({
          player_id: r.renter_player_id,
          type: 'system',
          title: 'Loyer garage impayé',
          message: `Votre location de garage (${r.daily_rent_light} ∞ ∞/jour) a été résiliée faute de fonds. Récupérez votre véhicule.`,
          link: `garage_rental:${r.id}`,
        });
        defaulted++;
        continue;
      }

      await balancesRepo().decrement({ player_id: r.renter_player_id }, 'infinite_light', r.daily_rent_light);
      await TransactionService.log({
        player_id: r.renter_player_id,
        category: 'rent',
        type: 'out',
        amount: r.daily_rent_light,
        currency: 'infinite_light',
        description: `Loyer garage (stockage véhicule)`,
      });

      r.last_rent_charged_at = now;
      await rentalRepo().save(r);
      charged++;
    }

    if (charged + defaulted > 0) {
      console.log(`[CRON] GarageRental: ${charged} loyers débités, ${defaulted} contrats résiliés`);
    }
    return { charged, defaulted };
  }

  /** Liste les contrats actifs d'un joueur (UI). */
  static async listActiveForPlayer(playerId: string): Promise<GarageRental[]> {
    return rentalRepo().find({
      where: { renter_player_id: playerId, status: 'active' },
      relations: ['business', 'vehicle'],
    });
  }

  /** Liste les véhicules stockés par business (pour le propriétaire). */
  static async listActiveForBusiness(businessId: string): Promise<GarageRental[]> {
    return rentalRepo().find({
      where: { business_id: businessId, status: 'active' },
      relations: ['vehicle', 'renter'],
    });
  }

  /**
   * Phase 15 v2 finition (2026-05-05) — businesses garage_storage à proximité
   * d'un point géographique pour le sélecteur UI. Tri par distance croissante,
   * limite par défaut 20 résultats.
   */
  static async listNearby(params: {
    lat: number;
    lon: number;
    radius_km?: number;
    limit?: number;
  }): Promise<Array<{
    id: string;
    name: string;
    location_lat: number;
    location_lon: number;
    distance_km: number;
  }>> {
    const radius = Math.max(0.5, Math.min(50, params.radius_km ?? 5));
    const limit = Math.max(1, Math.min(50, params.limit ?? 20));

    const businesses = await businessRepo()
      .createQueryBuilder('b')
      .where('b.type = :t', { t: 'garage_storage' })
      .andWhere('b.location_lat IS NOT NULL')
      .andWhere('b.location_lon IS NOT NULL')
      .getMany();

    const enriched = businesses
      .map((b) => {
        const lat = Number(b.location_lat);
        const lon = Number(b.location_lon);
        const distance = haversineDistance(params.lat, params.lon, lat, lon);
        return {
          id: b.id,
          name: b.name,
          location_lat: lat,
          location_lon: lon,
          distance_km: distance,
        };
      })
      .filter((b) => b.distance_km <= radius)
      .sort((a, b) => a.distance_km - b.distance_km)
      .slice(0, limit);

    return enriched;
  }
}
