import { Controller, Get, Post, Param, Req, UseGuards, BadRequestException } from '@nestjs/common';
import { QuestService } from './quest.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('quests')
@UseGuards(AuthGuard)
export class QuestController {
  constructor(
    private readonly questService: QuestService,
    @InjectRepository(Character)
    private readonly characterRepo: Repository<Character>,
  ) {}

  @Get('available')
  async getAvailable(@Req() req: Request) {
    const char = await this.getCharacter(req);
    return this.questService.getAvailable(char.id);
  }

  @Get('active')
  async getActive(@Req() req: Request) {
    const char = await this.getCharacter(req);
    return this.questService.getActive(char.id);
  }

  @Get('completed')
  async getCompleted(@Req() req: Request) {
    const char = await this.getCharacter(req);
    return this.questService.getCompleted(char.id);
  }

  @Post('accept/:id')
  async accept(@Param('id') questId: string, @Req() req: Request) {
    const char = await this.getCharacter(req);
    return this.questService.accept(questId, char.id);
  }

  @Post('claim/:id')
  async claim(@Param('id') playerQuestId: string, @Req() req: Request) {
    const char = await this.getCharacter(req);
    return this.questService.claim(playerQuestId, char.id);
  }

  @Post('abandon/:id')
  async abandon(@Param('id') playerQuestId: string, @Req() req: Request) {
    const char = await this.getCharacter(req);
    return this.questService.abandon(playerQuestId, char.id);
  }

  @Get('arcs')
  async getArcs(@Req() req: Request) {
    const char = await this.getCharacter(req);
    return this.questService.getArcs(char.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;
  }
}
