import { AppDataSource } from '../config/database';
import { Player } from '../models/Player';
import { PlayerHealth } from '../models/PlayerHealth';
import { HeatService } from './heat.service';

const playerRepo = () => AppDataSource.getRepository(Player);
const healthRepo = () => AppDataSource.getRepository(PlayerHealth);

/**
 * Service vacances (Phase 12, 2026-04-20).
 *
 * Le joueur peut mettre son compte sur pause 72h :
 *   - Aucune action possible (map, mission, travail, wizard, travel)
 *   - Aucune attaque subie (isOnVacation check dans attack handlers)
 *   - Chaleur temporairement 0 (sauvegardée pour restauration)
 *
 * À la fin naturelle : modal "J'espère que vous en avez bien profité".
 * Anticipé : modal "Déjà de retour ? Oui (débloque) / Non (poursuit 72h)".
 */
export class VacationService {
  static readonly DURATION_HOURS = 72;

  static async startVacation(playerId: string): Promise<{ resumes_at: string }> {
    const player = await playerRepo().findOneBy({ id: playerId });
    if (!player) throw new Error('Joueur introuvable');

    if (player.on_vacation_until && player.on_vacation_until > new Date()) {
      throw new Error('Déjà en vacances');
    }

    const health = await healthRepo().findOneBy({ player_id: playerId });
    if (health?.isHospitalized) throw new Error('Vous êtes hospitalisé — impossible de partir');
    if (health?.isImprisoned) throw new Error('Vous êtes incarcéré — impossible de partir');
    if (player.in_transit) throw new Error('En transit — impossible de partir');
    if (player.meditating_until && player.meditating_until > new Date()) {
      throw new Error('En méditation — impossible de partir');
    }

    const now = new Date();
    const resumes = new Date(now.getTime() + VacationService.DURATION_HOURS * 3600 * 1000);

    // Phase 16 (2026-04-22) — gel chaleur via HeatService (source unique U4)
    // freezePlayer sauvegarde la valeur actuelle dans vacation_previous_chaleur
    // et met chaleur à 0.
    await HeatService.freezePlayer(playerId);
    await playerRepo().update(playerId, {
      on_vacation_until: resumes,
      vacation_started_at: now,
    });

    return { resumes_at: resumes.toISOString() };
  }

  /**
   * Reprise vacances. Si early=true, termine anticipée. Sinon termine naturelle (vérif timer).
   * Restaure la chaleur à la valeur sauvegardée.
   */
  static async resumeVacation(playerId: string, early: boolean = false): Promise<{
    resumed: boolean;
    early: boolean;
    restored_chaleur: number | null;
  }> {
    const player = await playerRepo().findOneBy({ id: playerId });
    if (!player) throw new Error('Joueur introuvable');
    if (!player.on_vacation_until) return { resumed: false, early: false, restored_chaleur: null };

    const now = new Date();
    if (!early && player.on_vacation_until > now) {
      return { resumed: false, early: false, restored_chaleur: null };
    }

    // Phase 16 (2026-04-22) — restauration chaleur via HeatService (source unique U4)
    const restored = await HeatService.unfreezePlayer(playerId);

    await playerRepo().update(playerId, {
      on_vacation_until: null,
      vacation_started_at: null,
    });

    return { resumed: true, early, restored_chaleur: restored };
  }

  /** Garde globale : true si le joueur est actuellement en vacances. */
  static async isOnVacation(playerId: string): Promise<boolean> {
    const player = await playerRepo().findOneBy({ id: playerId });
    return !!(player?.on_vacation_until && player.on_vacation_until > new Date());
  }

  /**
   * CRON 60s : libère automatiquement les joueurs dont le timer est écoulé.
   * Restaure chaleur si possible.
   */
  static async resolveExpired(): Promise<number> {
    const expired = await playerRepo()
      .createQueryBuilder('p')
      .select(['p.id', 'p.vacation_previous_chaleur'])
      .where('p.on_vacation_until IS NOT NULL AND p.on_vacation_until <= NOW()')
      .getMany();

    let resolved = 0;
    for (const p of expired) {
      await VacationService.resumeVacation(p.id, false);
      resolved++;
    }
    return resolved;
  }
}
