import {
  Controller,
  Post,
  Body,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { RegisterDto } from './dto/register.dto';
import { RefreshTokenDto } from './dto/refresh-token.dto';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
import { CurrentUser } from '../common/decorators/current-user.decorator';

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

  @Post('login')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'User login' })
  async login(@Body() loginDto: LoginDto) {
    const result = await this.authService.login(loginDto);
    return {
      data: result,
      message: 'Login successful',
      statusCode: HttpStatus.OK,
    };
  }

  @Post('register')
  @ApiOperation({ summary: 'User registration' })
  async register(@Body() registerDto: RegisterDto) {
    const result = await this.authService.register(registerDto);
    return {
      data: result,
      message: 'Registration successful',
      statusCode: HttpStatus.CREATED,
    };
  }

  @Post('refresh')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Refresh access token' })
  async refresh(@Body() refreshTokenDto: RefreshTokenDto) {
    // We need to decode the refresh token to get the user ID
    // The JwtRefreshStrategy handles this, but for simplicity we'll decode manually
    const jwt = require('@nestjs/jwt');
    const { JwtService } = jwt;
    const jwtService = new JwtService();

    try {
      const payload = jwtService.decode(refreshTokenDto.refreshToken) as any;
      if (!payload || !payload.sub) {
        return {
          data: null,
          message: 'Invalid refresh token',
          statusCode: HttpStatus.UNAUTHORIZED,
        };
      }

      const tokens = await this.authService.refreshTokens(
        payload.sub,
        refreshTokenDto.refreshToken,
      );

      return {
        data: tokens,
        message: 'Token refreshed successfully',
        statusCode: HttpStatus.OK,
      };
    } catch {
      return {
        data: null,
        message: 'Invalid refresh token',
        statusCode: HttpStatus.UNAUTHORIZED,
      };
    }
  }

  @Post('logout')
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.OK)
  @ApiBearerAuth()
  @ApiOperation({ summary: 'User logout' })
  async logout(@CurrentUser('id') userId: string) {
    const result = await this.authService.logout(userId);
    return {
      data: null,
      message: result.message,
      statusCode: HttpStatus.OK,
    };
  }

  @Post('forgot-password')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Request password reset' })
  async forgotPassword(@Body('email') email: string) {
    const result = await this.authService.forgotPassword(email);
    return {
      data: null,
      message: result.message,
      statusCode: HttpStatus.OK,
    };
  }
}
