import { Body, Controller, Get, Param, Post, Req, Res, UseGuards, Session } from '@nestjs/common';
import { AuthService } from './auth.service';
import { JwtGuard, LocalGuard, PreviewGuard } from '@/common/guards';
import { ChangePasswordDto, RegisterUserDto, LoginUserDto } from './dto';
import { UserService } from '@/modules/user/user.service';
import * as svgCaptcha from 'svg-captcha';
import { CustomException, ErrorCode } from '@/common/exceptions/custom.exception';
import { ConfigService } from '@nestjs/config';
import { ApiBearerAuth } from '@nestjs/swagger';

@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private userService: UserService,
    private configService: ConfigService,
  ) {}

  @UseGuards(LocalGuard)
  @Post('login')
  async login(
    @Session() session: Record<string, any>,
    @Req() req: any,
    @Body() body: LoginUserDto,
  ) {
    // 预览环境下可快速登录，不用验证码
    // if (this.configService.get('IS_PREVIEW') === 'true' && body.isQuick) {
    //   return this.authService.login(req.user, req.session?.code);
    // }
    // 判断验证码是否正确
    // console.log('session', req.user, session, req, body.captcha);
    if (session.code?.toLocaleLowerCase() !== body.captcha?.toLocaleLowerCase()) {
      throw new CustomException(ErrorCode.ERR_10003);
    }

    return this.authService.login(req.user, req.session?.code);
  }

  @Post('register')
  @UseGuards(PreviewGuard)
  async register(@Body() user: RegisterUserDto) {
    return this.userService.create(user);
  }

  @Get('refresh/token')
  @ApiBearerAuth('JWT')
  @UseGuards(JwtGuard)
  async refreshToken(@Req() req: any) {
    return this.authService.generateToken(req.user);
  }

  @Post('current-role/switch/:roleCode')
  @ApiBearerAuth('JWT')
  @UseGuards(JwtGuard)
  async switchCurrentRole(@Req() req: any, @Param('roleCode') roleCode: string) {
    return this.authService.switchCurrentRole(req.user, roleCode);
  }

  @Post('logout')
  @ApiBearerAuth('JWT')
  @UseGuards(JwtGuard)
  async logout(@Req() req: any) {
    return this.authService.logout(req.user);
  }

  @Get('captcha')
  async createCaptcha(@Req() req, @Res() res) {
    const captcha = svgCaptcha.create({
      size: 4,
      fontSize: 40,
      width: 80,
      height: 40,
      background: '#fff',
      color: true,
    });
    req.session.code = captcha.text || '';
    res.type('image/svg+xml');
    res.send(captcha.data);
  }

  @Post('password')
  @ApiBearerAuth('JWT')
  @UseGuards(JwtGuard, PreviewGuard)
  async changePassword(@Req() req: any, @Body() body: ChangePasswordDto) {
    const ret = await this.authService.validateUser(req.user.username, body.oldPassword);
    if (!ret) {
      throw new CustomException(ErrorCode.ERR_10004);
    }
    // 修改密码
    // console.log('user', req.user);
    await this.userService.resetPassword(req.user.userId, body.newPassword);
    // 修改密码后退出登录
    await this.authService.logout(req.user);
    return true;
  }
}
