import {
  Body,
  Controller,
  Get,
  HttpCode,
  HttpStatus,
  Logger,
  NotFoundException,
  Post,
  Req,
  UseGuards,
} from "@nestjs/common";
import { ApiBearerAuth, ApiTags } from "@nestjs/swagger";
import { Request } from "express";
import { AuthService } from "./auth.service";
import { LoginAdminDto } from "./dto/login-admin.dto";
import { PasswordCheckingDto } from "./dto/password-checking.dto";
import { RegisterDto } from "./dto/register.dto";
import { ResendEmailDto } from "./dto/resend-email.dto";
import { ResetPasswordDto } from "./dto/reset-password.dto";
import { TokenDto } from "./dto/token.dto";
import { VerifyUserAccountDto } from "./dto/verify-user-account.dto";
import { JwtAuthGuard } from "./guards/jwt-auth.guard";
import { LoginStaffDto } from "./dto/login-staff.dto";
import { PinDto } from "./dto/pin.dto";
import { RolesGuard } from "src/share/guards/roles.guard";
import { Roles } from "src/share/decorators/roles.decorator";
import { RequestResetPasswordDto } from "./dto/request-reset-password.dto";
import { PinResetPasswordDto } from "./dto/pin-reset-password.dto";
import { ChangePasswordDto } from "./dto/change-password.dto";
import { ChangePinDto } from "./dto/change-pin.dto";
import { UsersService } from "../users/users.service";

@Controller("auth")
@ApiTags("auth")
export class AuthController {
  constructor(
    private userService: UsersService,
    private authService: AuthService,
  ) {}
  
  @Post("login")
  @HttpCode(HttpStatus.OK)
  async login(@Body() payload: LoginAdminDto) {
    const user = await this.authService.validateUser(
      payload
    );

    const token = await this.authService.createAccessToken({
      user: user.id,
      role: user.roleId,
    });

    const data_user = await this.userService.findOne(user.id);

    return {
      token: token,
      user: data_user
    };
  }

  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard)
  @Get("me")
  @HttpCode(HttpStatus.OK)
  async my(@Req() request: Request): Promise<any> {
    return request.user;
  }

  @Post("request-reset-password")
  @HttpCode(HttpStatus.OK)
  async requestResetPassword(@Body() payload: RequestResetPasswordDto): Promise<any> {
    return this.authService.requestResetPassword(payload.username);
  }

  @Post("reset-password")
  @HttpCode(HttpStatus.OK)
  async resetPassword(@Body() payload: ResetPasswordDto): Promise<any> {
    return this.authService.resetPassword(payload);
  }

  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles('staff')
  @Post("change-password")
  @HttpCode(HttpStatus.OK)
  async changePassword(@Req() request: Request, @Body() payload: ChangePasswordDto): Promise<any> {
    return this.authService.changePassword(request.user, payload);
  }
}
