import { Controller, Get, Post, Body, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { LoginDto, ChangePasswordDto } from './auth.dto';
import { Public, CurrentUser } from '../../shared/common/decorators';
import { JwtAuthGuard } from './guards';
import { jsonResponse } from '../../shared/common/filters';

@ApiTags('Auth')
@Controller()
export class AuthController {
  constructor(private auth: AuthService) {}

  @Public()
  @Post('player/auth/login')
  async playerLogin(@Body() dto: LoginDto) {
    const result = await this.auth.login(dto.username, dto.password, 'player');
    return jsonResponse(result);
  }

  @Public()
  @Post('admin/auth/login')
  async adminLogin(@Body() dto: LoginDto) {
    const result = await this.auth.login(dto.username, dto.password, 'admin');
    return jsonResponse(result);
  }

  @Public()
  @Post('agent/auth/login')
  async agentLogin(@Body() dto: LoginDto) {
    const result = await this.auth.login(dto.username, dto.password, 'agent');
    return jsonResponse(result);
  }

  @Public()
  @Post('manage/auth/login')
  async manageLogin(@Body() dto: LoginDto) {
    const result = await this.auth.staffLogin(dto.username, dto.password);
    return jsonResponse(result);
  }

  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @Get('manage/auth/me')
  async manageMe(
    @CurrentUser('id') userId: bigint,
    @CurrentUser('username') username: string,
    @CurrentUser('userType') userType: string,
    @CurrentUser('locale') locale: string | undefined,
    @CurrentUser('role') role: string | undefined,
    @CurrentUser('agentLevel') agentLevel: number | null | undefined,
  ) {
    return jsonResponse({
      id: userId.toString(),
      username,
      userType,
      locale,
      role,
      agentLevel: userType === 'AGENT' ? agentLevel ?? null : null,
    });
  }

  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @Post('player/auth/change-password')
  async playerChangePassword(
    @CurrentUser('id') userId: bigint,
    @Body() dto: ChangePasswordDto,
  ) {
    await this.auth.changePassword(userId, dto.oldPassword, dto.newPassword);
    return jsonResponse(null, 'Password changed');
  }
}
