import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Character } from '../character/entities/character.entity';
import { PlayerAchievement } from '../achievement/player-achievement.entity';
import { HallOfFame } from '../halloffame/hall-of-fame.entity';

@Injectable()
export class ProfileService {
  constructor(
    @InjectRepository(Character)
    private readonly characterRepo: Repository<Character>,
    @InjectRepository(PlayerAchievement)
    private readonly playerAchievementRepo: Repository<PlayerAchievement>,
    @InjectRepository(HallOfFame)
    private readonly hofRepo: Repository<HallOfFame>,
  ) {}

  async getProfile(characterId: string) {
    const character = await this.characterRepo.findOne({ where: { id: characterId } });
    if (!character) throw new BadRequestException('Personnage introuvable');

    // Achievement stats
    const achievements = await this.playerAchievementRepo.find({
      where: { characterId },
      relations: ['achievement'],
    });
    const unlocked = achievements.filter((a) => a.unlocked);

    // Total achievements count
    const totalCount = await this.playerAchievementRepo.manager
      .getRepository('Achievement')
      .count();

    // Badges from Hall of Fame
    const badges = await this.hofRepo.find({
      where: { characterId },
      order: { period: 'DESC' },
    });

    return {
      name: character.name,
      level: character.level,
      xp: character.xp,
      gold: character.gold,
      activeTitle: character.activeTitle,
      stats: {
        force: character.force,
        agilite: character.agilite,
        intelligence: character.intelligence,
        chance: character.chance,
        vitalite: character.vitalite,
      },
      achievements: {
        unlocked: unlocked.length,
        total: totalCount,
        percentage: totalCount > 0 ? Math.floor((unlocked.length / totalCount) * 100) : 0,
      },
      badges: badges.map((b) => ({ badge: b.badge, period: b.period, rank: b.rank })),
    };
  }

  async setActiveTitle(characterId: string, title: string) {
    // Verify the player has unlocked this title
    if (title) {
      const hasTitle = await this.playerAchievementRepo
        .createQueryBuilder('pa')
        .innerJoin('pa.achievement', 'a')
        .where('pa.character_id = :characterId', { characterId })
        .andWhere('pa.unlocked = true')
        .andWhere('a.reward_title = :title', { title })
        .getCount();

      if (!hasTitle) {
        throw new BadRequestException('Titre non débloqué');
      }
    }

    await this.characterRepo.update(characterId, { activeTitle: title || null });
    return { activeTitle: title || null };
  }
}
