import { Controller, Get, Put, Body, Req, UseGuards, BadRequestException } from '@nestjs/common';
import { ProfileService } from './profile.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';

@Controller('profile')
export class ProfileController {
  constructor(
    private readonly profileService: ProfileService,
    @InjectRepository(Character)
    private readonly characterRepo: Repository<Character>,
  ) {}

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

  @Put('title')
  @UseGuards(AuthGuard)
  async setTitle(@Body('title') title: string, @Req() req: Request) {
    const character = await this.getCharacter(req);
    return this.profileService.setActiveTitle(character.id, title);
  }

  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;
  }
}
