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 méditation (Phase 7, 2026-04-20) — lieu de culte (amenity=place_of_worship).
 *
 * Le joueur clique "Aller méditer" :
 *  - Check : pas hospitalisé, pas emprisonné, pas in_transit, pas déjà en méditation.
 *  - Set player.meditating_until = now + 8h.
 *  - Pendant 8h : AUCUNE action (map/mission/travail/travel/wizard) autorisée.
 *  - À la fin (CRON 60s), on retire 1 pt chaleur et on clear meditating_until.
 */
export class MeditationService {
  static readonly DURATION_HOURS = 8;

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

    if (player.meditating_until && player.meditating_until > new Date()) {
      throw new Error('Vous êtes déjà en méditation');
    }

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

    const until = new Date(Date.now() + MeditationService.DURATION_HOURS * 3600 * 1000);
    await playerRepo().update(playerId, { meditating_until: until });

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

  /** Retourne vrai si le joueur est actuellement en méditation. */
  static async isMeditating(playerId: string): Promise<boolean> {
    const player = await playerRepo().findOneBy({ id: playerId });
    return !!(player?.meditating_until && player.meditating_until > new Date());
  }

  /**
   * CRON 60s : résoudre les méditations expirées.
   * Effet : −1 chaleur + clear meditating_until.
   */
  static async resolveExpired(): Promise<number> {
    const now = new Date();
    const expired = await playerRepo()
      .createQueryBuilder('p')
      .select(['p.id'])
      .where('p.meditating_until IS NOT NULL AND p.meditating_until <= :now', { now })
      .getMany();

    let resolved = 0;
    for (const p of expired) {
      await playerRepo().update(p.id, { meditating_until: null });
      // Phase 16 (2026-04-22) — migré vers HeatService (U4, source unique)
      await HeatService.applyToPlayer(p.id, -1, 'meditation_end', 'place_of_worship');
      resolved++;
    }
    return resolved;
  }
}
