import {
  Body,
  Controller,
  Post,
  ValidationPipe,
  UsePipes,
  UnauthorizedException,
  Res,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';
import { LoginUserDto } from './logins.dto';
import { AuthorizationService } from './authorization.service';
import { CustomException } from 'src/utils/response';
import { ForgotPasswordDto } from './dtos/forgot-password.dto';
import { STUDENT_MESSAGES } from 'src/constants/student';
import { Response } from 'express';

/**
 * AuthorizationController - Controller for authentication and authorization operations
 *
 * This controller handles user authentication flows including:
 * - User login with credentials
 * - Password reset requests
 * - Other authorization-related operations
 *
 * All routes are prefixed with '/authorization' as defined in @Controller decorator.
 *
 * @example
 * // Base URL for all routes in this controller
 * POST /authorization/login
 * POST /authorization/forgot-password
 *
 * @note The controller is currently empty - endpoints need to be implemented
 * @note Consider splitting into AuthController and PasswordController for clarity
 */
@ApiTags('Authorization') // Groups endpoints under 'Authorization' in Swagger UI
@Controller('') // Base route path: /authorization
export class AuthorizationController {
  /**
   * Creates an instance of AuthorizationController
   *
   * @param authService - Authorization service for business logic
   */
  constructor(private readonly authService: AuthorizationService) {}

  // auth.controller.ts
  // @Post('login')
  // async login(@Body() body: any) {
  //   const user = await this.authService.validateUser(body.email, body.password);

  //   if (!user) {
  //     throw new UnauthorizedException('Invalid credentials');
  //   }

  //   return this.authService.login(user);
  // }
  @Post('login')
  async login(@Body() body: any, @Res({ passthrough: true }) res: Response) {
    const user = await this.authService.validateUser(body.email, body.password);

    if (!user) {
      throw new UnauthorizedException('Invalid credentials');
    }

    const result = await this.authService.login(user);
    const token = result.access_token;
    console.log({result})
    // ✅ THIS is where cookie is set
    res.cookie('access_token', token, {
      httpOnly: true, // 🔐 secure
      secure: false, // true in production (HTTPS)
      sameSite: 'lax',
    });

    return {access_token: token};
  }

  @Post('register')
  async register(@Body() body: any) {
    return this.authService.register(body);
  }

  /**
   * Example login endpoint implementation (to be added):
   *
   * @Post('login')
   * @ApiOperation({ summary: 'User login', description: 'Authenticate user with credentials' })
   * @ApiBody({ type: LoginUserDto })
   * @ApiResponse({ status: 200, description: 'Login successful' })
   * @ApiResponse({ status: 401, description: 'Invalid credentials' })
   * @UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
   * async login(@Body() loginDto: LoginUserDto) {
   *   try {
   *     const result = await this.authService.login(loginDto);
   *     return result;
   *   } catch (error) {
   *     throw new CustomException(error.message, error.status);
   *   }
   * }
   */

  /**
   * Example forgot password endpoint implementation (to be added):
   *
   * @Post('forgot-password')
   * @ApiOperation({ summary: 'Forgot password', description: 'Request password reset' })
   * @ApiBody({ type: ForgotPasswordDto })
   * @ApiResponse({ status: 200, description: 'Reset instructions sent' })
   * @ApiResponse({ status: 404, description: 'User not found' })
   * @UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
   * async forgotPassword(@Body() forgotPasswordDto: ForgotPasswordDto) {
   *   try {
   *     const message = await this.authService.initiatePasswordReset(forgotPasswordDto.email);
   *     return { message: STUDENT_MESSAGES.PASSWORD_RESET_SENT };
   *   } catch (error) {
   *     throw new CustomException(error.message, error.status);
   *   }
   * }
   */
}
