import { Controller, Get, UseGuards, Req, BadRequestException } from '@nestjs/common';
import { MonsterService } from './monster.service';
import { AuthGuard } from '../auth/guards/auth.guard';
import { Request } from 'express';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Character } from '../character/entities/character.entity';
import { QuestArc } from '../quest/quest-arc.entity';
import { PlayerQuestArc } from '../quest/player-quest-arc.entity';
import { getUnlockedZones } from '../common/zone-access';

@Controller('monsters')
export class MonsterController {
  constructor(
    private readonly monsterService: MonsterService,
    @InjectRepository(Character)
    private readonly characterRepo: Repository<Character>,
    @InjectRepository(QuestArc)
    private readonly arcRepo: Repository<QuestArc>,
    @InjectRepository(PlayerQuestArc)
    private readonly playerArcRepo: Repository<PlayerQuestArc>,
  ) {}

  @Get('bestiary')
  async getBestiary() {
    const allMonsters = await this.monsterService.findAll();
    return allMonsters;
  }

  @Get('zones')
  @UseGuards(AuthGuard)
  async getZones(@Req() req: Request) {
    const user = (req as any).user;
    const char = await this.characterRepo.findOne({ where: { userId: user.id } });
    if (!char) throw new BadRequestException('Aucun personnage');

    const unlockedZones = await getUnlockedZones(char.id, this.arcRepo, this.playerArcRepo);

    const ALL_ZONES = [
      { id: 'marais', name: 'Les Marais', emoji: '🌿', minLevel: 1 },
      { id: 'egouts', name: 'Les Égouts', emoji: '🕳️', minLevel: 4 },
      { id: 'desert', name: 'Le Désert', emoji: '🏜️', minLevel: 8 },
    ];

    return ALL_ZONES.map(z => ({
      ...z,
      unlocked: unlockedZones.includes(z.id),
    }));
  }

  @Get()
  @UseGuards(AuthGuard)
  async findAll(@Req() req: Request) {
    const user = (req as any).user;
    const char = await this.characterRepo.findOne({ where: { userId: user.id } });
    if (!char) throw new BadRequestException('Aucun personnage');

    const unlockedZones = await getUnlockedZones(char.id, this.arcRepo, this.playerArcRepo);
    const allMonsters = await this.monsterService.findAll();

    return allMonsters.filter(m => unlockedZones.includes(m.zone));
  }
}
