import { AppDataSource } from '../config/database';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerHealth } from '../models/PlayerHealth';
import { PlayerInventory } from '../models/PlayerInventory';
import { Player } from '../models/Player';
import { TransactionService } from './transaction.service';

const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const healthRepo = () => AppDataSource.getRepository(PlayerHealth);
const inventoryRepo = () => AppDataSource.getRepository(PlayerInventory);
const playerRepo = () => AppDataSource.getRepository(Player);

export class HealthService {
  static async hasCareCard(playerId: string): Promise<boolean> {
    const card = await inventoryRepo().findOne({
      where: { player_id: playerId, item_subtype: 'carte_soin', storage_condition: 'on_person' as any },
    });
    return !!card && (card.quantity ?? 0) > 0;
  }

  /**
   * Phase 8 v2 health refactor (2026-05-01) — Reset PV à 100 + sortie hôpital.
   *
   * Single source : ne touche QUE player_health.physical_health.
   * La colonne player_gauges.sante_physique (legacy) sera droppée en
   * migration 071 quand tous les services auront été migrés.
   *
   * Note : healing_pts_remaining + healing_next_tick_at sont aussi reset
   * pour stopper proprement un soin progressif en cours (urgentiste ou
   * hôpital).
   */
  static async healToFull(playerId: string): Promise<void> {
    const health = await healthRepo().findOne({ where: { player_id: playerId } });
    const payload = {
      physical_health: 100,
      hospitalized_until: null,
      healing_pts_remaining: 0,
      healing_next_tick_at: null,
    };
    if (health) {
      await healthRepo().update({ player_id: playerId }, payload);
    } else {
      await healthRepo().save(healthRepo().create({ player_id: playerId, ...payload }));
    }
  }

  /**
   * Phase 8 v2 health refactor (2026-05-01) — Single source of truth.
   *
   * Set la valeur exacte de physical_health (0-100). À utiliser pour les
   * deltas exacts (combat damage, set explicit). Pour reset complet à
   * 100 + sortie d'hôpital, préférer `healToFull`. Pour delta relatif
   * avec clamp atomique, préférer `adjustHp`.
   */
  static async setHp(playerId: string, hp: number): Promise<void> {
    const clamped = Math.max(0, Math.min(100, Math.floor(hp)));
    await healthRepo().update({ player_id: playerId }, { physical_health: clamped });
  }

  /**
   * Phase 8 v2 health refactor (2026-05-01) — Delta relatif atomique.
   *
   * UPDATE physical_health avec LEAST/GREATEST 0-100 en SQL pur. Évite
   * la race condition lecture-puis-écriture si plusieurs callers
   * adjustent en parallèle (food, combat, prison-activity).
   *
   * Tous les callers qui touchaient sante_physique seul doivent maintenant
   * passer par cette fonction (food, prison effects, missions failure).
   */
  static async adjustHp(playerId: string, delta: number): Promise<void> {
    if (!Number.isFinite(delta) || delta === 0) return;
    const d = Math.floor(delta);
    await healthRepo()
      .createQueryBuilder()
      .update()
      .set({
        physical_health: () => `LEAST(100, GREATEST(0, physical_health + ${d}))`,
      })
      .where('player_id = :pid', { pid: playerId })
      .execute();
  }

  static async hospitalHeal(playerId: string): Promise<{ cost: number; used_care_card: boolean }> {
    const hasCard = await HealthService.hasCareCard(playerId);
    // Phase 8.5d (2026-04-29) — Frais hardcoded 100 → GameSettings 3000 (default)
    const { GameSettingsService } = await import('./game-settings.service');
    const fee = await GameSettingsService.get<number>('hospital.exit_fee_default', 3000);
    const cost = hasCard ? 0 : fee;

    if (cost > 0) {
      const balances = await balancesRepo().findOne({ where: { player_id: playerId } });
      if (!balances) throw new Error('Balances introuvables');
      if (Number(balances.infinite_light) < cost) throw new Error('Fonds insuffisants');
      await balancesRepo().decrement({ player_id: playerId }, 'infinite_light', cost);
      await TransactionService.log({
        player_id: playerId,
        category: 'health',
        type: 'out',
        amount: cost,
        currency: 'infinite_light',
        description: `Soins hôpital`,
      });
    }

    await HealthService.healToFull(playerId);
    return { cost, used_care_card: hasCard };
  }

  static async doctorCall(playerId: string): Promise<{ cost: number; used_care_card: boolean }> {
    const player = await playerRepo().findOne({ where: { id: playerId } });
    if (!player) throw new Error('Joueur introuvable');
    const hasDoctor = Array.isArray(player.contacts) && player.contacts.some((c) => c?.player_id === 'npc:doctor');
    if (!hasDoctor) throw new Error('Contact docteur indisponible');

    const hasCard = await HealthService.hasCareCard(playerId);
    const cost = hasCard ? 0 : 50;

    if (cost > 0) {
      const balances = await balancesRepo().findOne({ where: { player_id: playerId } });
      if (!balances) throw new Error('Balances introuvables');
      if (Number(balances.infinite_light) < cost) throw new Error('Fonds insuffisants');
      await balancesRepo().decrement({ player_id: playerId }, 'infinite_light', cost);
      await TransactionService.log({
        player_id: playerId,
        category: 'health',
        type: 'out',
        amount: cost,
        currency: 'infinite_light',
        description: `Appel docteur`,
      });
    }

    await HealthService.healToFull(playerId);
    return { cost, used_care_card: hasCard };
  }
}

