import { Controller, Get, Post, Param, Req, UseGuards } from '@nestjs/common';
import { AchievementService } from './achievement.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 { BadRequestException } from '@nestjs/common';

@Controller('achievements')
export class AchievementController {
  constructor(
    private readonly achievementService: AchievementService,
    @InjectRepository(Character)
    private readonly characterRepo: Repository<Character>,
  ) {}

  @Get()
  findAll() {
    return this.achievementService.findAll();
  }

  @Get('me')
  @UseGuards(AuthGuard)
  async getMyProgress(@Req() req: Request) {
    const character = await this.getCharacter(req);
    return this.achievementService.getMyProgress(character.id);
  }

  @Post('claim/:id')
  @UseGuards(AuthGuard)
  async claim(@Param('id') achievementId: string, @Req() req: Request) {
    const character = await this.getCharacter(req);
    return this.achievementService.claim(achievementId, character.id);
  }

  private async getCharacter(req: Request): Promise<Character> {
    const user = (req as any).user;
    const character = await this.characterRepo.findOne({ where: { userId: user.id } });
    if (!character) throw new BadRequestException('Aucun personnage trouvé');
    return character;
  }
}
