import { AppDataSource } from '../config/database';
import { Player } from '../models/Player';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerGauges } from '../models/PlayerGauges';
import { PlayerHealth } from '../models/PlayerHealth';
import { PlayerInventory } from '../models/PlayerInventory';
import { PlayerSkills } from '../models/PlayerSkills';
import { Journey } from '../models/Journey';
import { MissionProgress } from '../models/MissionProgress';

export interface FullPlayerState {
  player: Omit<Player, 'password_hash' | 'oauth_id'>;
  gauges: PlayerGauges | null;
  balances: PlayerBalances | null;
  health: PlayerHealth | null;
  skills: PlayerSkills[];
  inventory: PlayerInventory[];
  activeJourney: Journey | null;
  activeMission: MissionProgress | null;
}

export class PlayerService {
  static async getFullPlayerState(playerId: string): Promise<FullPlayerState | null> {
    const playerRepo = AppDataSource.getRepository(Player);
    const player = await playerRepo.findOne({
      where: { id: playerId },
      relations: ['gauges', 'balances', 'health'],
    });
    if (!player) return null;

    const [skills, inventory, activeJourney, activeMission] = await Promise.all([
      AppDataSource.getRepository(PlayerSkills).find({
        where: { player_id: playerId },
        order: { skill_id: 'ASC' },
      }),
      AppDataSource.getRepository(PlayerInventory).find({
        where: { player_id: playerId },
      }),
      AppDataSource.getRepository(Journey).findOne({
        where: { player_id: playerId, status: 'in_transit' as any },
        order: { created_at: 'DESC' },
      }),
      AppDataSource.getRepository(MissionProgress).findOne({
        where: { player_id: playerId, status: 'in_progress' as any },
        order: { started_at: 'DESC' },
      }),
    ]);

    const { password_hash, oauth_id, ...safePlayer } = player as any;

    return {
      player: safePlayer,
      gauges: player.gauges ?? null,
      balances: player.balances ?? null,
      health: player.health ?? null,
      skills,
      inventory,
      activeJourney: activeJourney ?? null,
      activeMission: activeMission ?? null,
    };
  }

  static async withFullState<T extends Record<string, unknown>>(
    playerId: string,
    responseData: T,
  ): Promise<T & { playerState: FullPlayerState | null }> {
    const playerState = await PlayerService.getFullPlayerState(playerId);
    return { ...responseData, playerState };
  }
}

