/**
 * Phase 17 (2026-05-04) — MedicService.
 *
 * Médecin perso recruté via POI santé (hôpital ou clinique).
 * Limité à 1 médecin attitré par PLAYER (pas gang/cartel — concept médecin
 * personnel n'a pas de sens pour ces scopes).
 *
 * Mécaniques :
 *   1. Heal passif : +1 PV / heure (cron hourly), partout (hôpital/prison
 *      OK, cumul accéléré possible). Tarif fourchette 80-140 ∞/jour
 *      négocié à l'embauche, prélevé daily par cron paie. Soigne pareil
 *      quel que soit le tarif (consigne user "soigne pareil").
 *   2. On-call : appel téléphonique payant. Joueur choisit le nombre de
 *      PV à acheter (0 à max manquant). Paye 100 ∞ par PV (shadow OU
 *      light, au choix). Livraison +1 PV/min jusqu'à atteindre le target.
 */

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

const attRepo = () => AppDataSource.getRepository(SpecialistAttachment);
const phRepo = () => AppDataSource.getRepository(PlayerHealth);
const balancesRepo = () => AppDataSource.getRepository(PlayerBalances);
const notifRepo = () => AppDataSource.getRepository(Notification);

const ON_CALL_COST_PER_PV = 100;     // ∞ / PV
const ON_CALL_DELIVERY_RATE_MIN = 1; // 1 PV / minute

export class MedicService {

  /**
   * CRON hourly — passive heal +1 PV pour chaque attachment medic actif
   * dont l'owner est un player avec PV < 100.
   *
   * Cumul OK avec autres systèmes (hospital tick, urgentiste session) :
   * la consigne user dit "si on cumule des methodes de guerison ca va
   * plus vite".
   */
  static async tickPassiveHeal(): Promise<{ healed: number; released: number }> {
    const attachments = await attRepo()
      .createQueryBuilder('a')
      .innerJoinAndSelect('a.specialist', 's')
      .where('a.is_active = true')
      .andWhere('s.role = :r', { r: 'medic' })
      .andWhere('a.owner_type = :t', { t: 'player' })
      .getMany();

    let healed = 0;
    let triggerRelease = false;
    for (const att of attachments) {
      try {
        const ph = await phRepo().findOneBy({ player_id: att.owner_id });
        if (!ph) continue;
        const current = Number(ph.physical_health ?? 0);
        if (current >= 100) continue;

        const newPv = Math.min(100, current + 1);
        await phRepo().update(
          { player_id: att.owner_id },
          { physical_health: newPv },
        );
        att.passive_heal_last_at = new Date();
        await attRepo().save(att);
        healed++;

        // Phase 17.2 (2026-05-05) — Si le tick fait passer les PV à 100
        // ET que le joueur est hospitalisé, on déclenche immédiatement
        // HospitalService.processReleases (au lieu d'attendre le prochain
        // tick cron 60s). Consigne user verbatim Q2 A : "si joueur à 100
        // sortie ou suite si police tribunal ou gign (donc si on cumule
        // des methodes de guerison ca va plus vite)".
        // processReleases inclut déjà le check `physical_health >= 100`
        // dans sa where clause, donc le player sera bien libéré.
        if (newPv >= 100 && ph.hospitalized_until && new Date(ph.hospitalized_until).getTime() > Date.now()) {
          triggerRelease = true;
        }
      } catch (err) {
        console.error('[Medic] tickPassiveHeal failed for', att.id, ':', (err as Error).message);
      }
    }

    // Trigger early release pour tous les players ayant atteint 100 PV
    // (batch unique, évite N appels à processSinglePlayer)
    let released = 0;
    if (triggerRelease) {
      try {
        const { HospitalService } = await import('./hospital.service');
        const r = await HospitalService.processReleases();
        released = r.released;
      } catch (err) {
        console.error('[Medic] early release trigger failed:', (err as Error).message);
      }
    }

    return { healed, released };
  }

  /**
   * Endpoint on-call : appel téléphonique au médecin perso.
   *
   * Le joueur choisit le nombre de PV (0 < N ≤ PV manquants) et la devise
   * (shadow OU light). Paie 100 × N ∞, puis le médecin livre 1 PV/min.
   *
   * On programme la livraison via PlayerHealth.healing_pts_remaining +
   * healing_next_tick_at (mécanisme existant, partagé avec urgentiste).
   * La cron urgentiste tick déjà toutes les 60s — on s'y greffe.
   */
  static async callOnDemand(
    playerId: string,
    pointsRequested: number,
    currency: 'shadow' | 'light' = 'shadow',
  ): Promise<{
    accepted: boolean;
    points_to_deliver: number;
    cost: number;
    currency: 'shadow' | 'light';
    estimated_minutes: number;
    message: string;
  }> {
    // Vérifier que le player a un médecin attaché actif
    const att = await attRepo()
      .createQueryBuilder('a')
      .innerJoinAndSelect('a.specialist', 's')
      .where('a.owner_type = :t AND a.owner_id = :id', { t: 'player', id: playerId })
      .andWhere('a.is_active = true')
      .andWhere('s.role = :r', { r: 'medic' })
      .getOne();
    if (!att) {
      return {
        accepted: false,
        points_to_deliver: 0,
        cost: 0,
        currency,
        estimated_minutes: 0,
        message: 'Aucun médecin perso attaché — recrute-en un dans une clinique ou un hôpital.',
      };
    }

    // PV actuels
    const ph = await phRepo().findOneBy({ player_id: playerId });
    const current = Number(ph?.physical_health ?? 0);
    const missing = Math.max(0, 100 - current);
    if (missing === 0) {
      return {
        accepted: false,
        points_to_deliver: 0,
        cost: 0,
        currency,
        estimated_minutes: 0,
        message: 'Tu es déjà à 100 PV.',
      };
    }

    // Clamp pointsRequested ∈ [1, missing]
    const N = Math.max(1, Math.min(missing, Math.floor(pointsRequested)));
    const cost = N * ON_CALL_COST_PER_PV;

    // Vérifier solvabilité dans la devise CHOISIE (on n'utilise PAS
    // PaymentService.debitMix qui force shadow-first — ici l'user a
    // explicitement choisi la devise, on respecte son choix).
    const balances = await balancesRepo().findOneBy({ player_id: playerId });
    const available = Number(
      currency === 'shadow' ? balances?.infinite_shadow : balances?.infinite_light,
    ) || 0;
    if (available < cost) {
      return {
        accepted: false,
        points_to_deliver: N,
        cost,
        currency,
        estimated_minutes: 0,
        message: `Fonds insuffisants en ∞ ${currency} : ${available.toLocaleString('fr-FR')} dispo, ${cost.toLocaleString('fr-FR')} requis.`,
      };
    }

    // Débit single-currency (respecte le choix joueur)
    const colName = currency === 'shadow' ? 'infinite_shadow' : 'infinite_light';
    await balancesRepo().createQueryBuilder().update()
      .set({ [colName]: () => `GREATEST(0, ${colName} - ${cost})` })
      .where('player_id = :id', { id: playerId })
      .execute();
    await TransactionService.log({
      player_id: playerId,
      category: 'health',
      type: 'out',
      amount: cost,
      currency: currency === 'shadow' ? 'infinite_shadow' : 'infinite_light',
      description: `On-call médecin (${N} PV × ${ON_CALL_COST_PER_PV} ∞ ${currency})`,
    });

    // Programme la livraison via PlayerHealth.healing_pts_remaining +
    // healing_next_tick_at. La cron existante (urgentist-care-cron toutes
    // les 60s, ou le cron health.service tick) appliquera +1 PV/min.
    const additionalPts = N;
    const nextTick = new Date(Date.now() + 60 * 1000); // dans 1 minute
    await phRepo().update(
      { player_id: playerId },
      {
        healing_pts_remaining: () => `COALESCE(healing_pts_remaining, 0) + ${additionalPts}` as any,
        healing_next_tick_at: nextTick,
      } as any,
    );

    // Notif
    try {
      await notifRepo().save(notifRepo().create({
        player_id: playerId,
        type: 'system',
        title: `${att.specialist.name} en route`,
        message:
          `${att.specialist.name} arrive. ${N} PV à 1/min, ${cost.toLocaleString('fr-FR')} ∞ ${currency} prélevés. ` +
          `Livraison estimée : ${N} min.`,
      }));
    } catch { /* silent */ }

    return {
      accepted: true,
      points_to_deliver: N,
      cost,
      currency,
      estimated_minutes: N,
      message: `${att.specialist.name} arrive — ${N} PV livrés à raison de 1 PV/min.`,
    };
  }
}
