import { AppDataSource } from '../config/database';
import { GangServiceUsage, GangServiceType } from '../models/GangServiceUsage';
import { PlayerBalances } from '../models/PlayerBalances';
import { Player } from '../models/Player';
import { Notification } from '../models/Notification';
import { TransactionService } from './transaction.service';
import { ReinforcementService } from './reinforcement.service';
import { BankLoanService } from './bank-loan.service';

const usageRepo = () => AppDataSource.getRepository(GangServiceUsage);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const playerRepo = () => AppDataSource.getRepository(Player);
const notifRepo = () => AppDataSource.getRepository(Notification);

/**
 * Services d'un gang NPC au joueur :
 *   - Renfort : 3×/semaine glissante, tarif progressif (gratuit, gratuit, 1000 ∞).
 *   - Dépannage : 1×/mois glissant, 100 ∞/9999 xp.
 *   - Crédit : plafond = 1000 × missions gang complétées.
 *
 * Réponses progressives (CDC) :
 *   RENFORT 1 : lightbox d'intro, bouton Appeler.
 *   RENFORT 2 : "Ça doit chauffer par chez toi…", Confirmer / Annuler.
 *   RENFORT 3 : "Avec tout le respect qu'on te porte, ça a ses frais…", Payer 1000 ∞.
 *   RENFORT 4 : "Ça fait déjà 3 fois cette semaine…", bouton Retour.
 */
export class GangServiceUsageService {
  static readonly DEPANNAGE_WINDOW_DAYS = 30;

  static async countRecent(
    playerId: string,
    gangId: string,
    service: GangServiceType,
    windowHours: number,
  ): Promise<number> {
    const since = new Date(Date.now() - windowHours * 3600 * 1000);
    return usageRepo().createQueryBuilder('u')
      .where('u.player_id = :pid AND u.gang_id = :gid AND u.service_type = :st', {
        pid: playerId, gid: gangId, st: service,
      })
      .andWhere('u.used_at >= :since', { since })
      .getCount();
  }

  /** Niveau progressif du lightbox renfort (1..4). Null si limite dépassée. */
  static async reinforcementStage(playerId: string, gangId: string): Promise<1 | 2 | 3 | 4> {
    const used = await GangServiceUsageService.countRecent(playerId, gangId, 'reinforcement', 168);
    if (used === 0) return 1;
    if (used === 1) return 2;
    if (used === 2) return 3;
    return 4; // 3+ → refus
  }

  /**
   * Exécute la demande de renfort (stage 1 gratuit, 2 gratuit, 3 = 1000 ∞).
   * Le frontend doit avoir consommé le lightbox correspondant avant d'appeler.
   */
  static async requestReinforcement(
    playerId: string,
    gangId: string,
    ownerType: 'player' | 'cartel',
    ownerId: string,
    centerLat: number,
    centerLng: number,
    influenceRadiusM: number,
  ): Promise<{ success: boolean; stage: number; spawned: number; cost: number; message: string }> {
    const stage = await GangServiceUsageService.reinforcementStage(playerId, gangId);
    if (stage === 4) return { success: false, stage: 4, spawned: 0, cost: 0, message: "Vous avez épuisé vos demandes de renfort (3/semaine)." };

    const cost = stage === 3 ? 1000 : 0;
    if (cost > 0) {
      const b = await balancesRepo().findOneBy({ player_id: playerId });
      const combined = (Number(b?.infinite_shadow || 0) + Number(b?.infinite_light || 0));
      if (combined < cost) {
        return { success: false, stage, spawned: 0, cost, message: 'Fonds insuffisants pour payer le renfort.' };
      }
      const shadow = Number(b?.infinite_shadow || 0);
      const fromShadow = Math.min(shadow, cost);
      const fromLight = cost - fromShadow;
      await balancesRepo().createQueryBuilder().update()
        .set({
          infinite_shadow: () => `GREATEST(0, infinite_shadow - ${fromShadow})`,
          infinite_light: () => `GREATEST(0, infinite_light - ${fromLight})`,
        })
        .where('player_id = :id', { id: playerId })
        .execute();
      await TransactionService.log({
        player_id: playerId,
        category: 'gang',
        type: 'out',
        amount: cost,
        currency: 'infinite_shadow',
        description: `Service renfort gang (${cost} ∞)`,
      });
    }

    const { spawned } = await ReinforcementService.spawn(
      playerId, gangId, ownerType, ownerId, centerLat, centerLng, influenceRadiusM,
    );

    return { success: true, stage, spawned, cost, message: `${spawned} renforts envoyés.` };
  }

  // ──────────────────────────────────────────────────────────
  // Dépannage (1 × / 30 jours glissants)
  // ──────────────────────────────────────────────────────────

  static async requestDepannage(
    playerId: string, gangId: string,
  ): Promise<{ success: boolean; amount: number; message: string }> {
    const used = await GangServiceUsageService.countRecent(playerId, gangId, 'depannage', 24 * 30);
    if (used > 0) {
      return { success: false, amount: 0, message: "Faudrait pas abuser mon gars…" };
    }
    const player = await playerRepo().findOneBy({ id: playerId });
    if (!player) return { success: false, amount: 0, message: 'Joueur introuvable' };
    const xp = Number(player.experience) || 0;
    const tranches = Math.floor(xp / 9999);
    const amount = 100 * tranches;
    if (amount <= 0) {
      return { success: false, amount: 0, message: 'Pas assez d\'XP pour un dépannage.' };
    }
    await balancesRepo().increment({ player_id: playerId }, 'infinite_shadow', amount);
    await TransactionService.log({
      player_id: playerId, category: 'gang', type: 'in',
      amount, currency: 'infinite_shadow',
      description: 'Dépannage gang',
    });
    await usageRepo().save(usageRepo().create({
      player_id: playerId, gang_id: gangId, service_type: 'depannage', amount,
    }));
    return { success: true, amount, message: `On peut te dépanner un peu oui. Dépanné de ${amount.toLocaleString('fr-FR')} ∞.` };
  }

  // ──────────────────────────────────────────────────────────
  // Crédit gang (plafond = 1000 × missions complétées)
  // ──────────────────────────────────────────────────────────

  static async requestCredit(playerId: string, gangId: string, amount: number) {
    return BankLoanService.requestGangLoan(playerId, gangId, amount);
  }
}
