import {
  Controller,
  Post,
  Body,
  UnauthorizedException,
  UseGuards,
  Get,
  Request,
  Logger,
  BadRequestException,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginDto } from '../dto/login.dto';
import { CreateUserDto } from '../dto/create-user.dto';
import { JwtAuthGuard } from './jwt-auth.guard';
import { AdminGuard } from './admin.guard';
//@UseGuards(JwtAuthGuard, AdminGuard)
@Controller('auth')
export class AuthController {
  private readonly logger = new Logger(AuthController.name);

  constructor(private authService: AuthService) {
    this.logger.log('AuthController initialized');
  }

  @Post('login')
  async login(@Body() loginDto: LoginDto) {
    this.logger.log('=== Login endpoint hit ===');
    this.logger.debug('Raw request body:', {
      username: loginDto.username,
      email: loginDto.email,
      hasPassword: !!loginDto.password,
    });

    const email = loginDto.getEmail();
    this.logger.debug('Normalized login request:', {
      email,
      hasPassword: !!loginDto.password,
    });
    
    try {
      this.logger.debug('Calling AuthService.validateUser...');
      const user = await this.authService.validateUser(
        email,
        loginDto.password,
      );
      
      if (!user) {
        this.logger.warn(`Login failed: Invalid credentials for ${email}`);
        throw new UnauthorizedException('Invalid email or password');
      }
      
      this.logger.debug('User validated successfully:', {
        id: user.id,
        email: user.email,
        name: user.name,
        isAdmin: user.isAdmin,
      });

      this.logger.debug('Calling AuthService.login...');
      const result = await this.authService.login(user);
      
      this.logger.debug('Login successful, returning response:', {
        hasAccessToken: !!result.access_token,
        user: {
          id: result.user.id,
          email: result.user.email,
          name: result.user.name,
          isAdmin: result.user.isAdmin,
        },
      });
      
      return result;
    } catch (error) {
      if (error instanceof UnauthorizedException) {
        throw error;
      }
      
      this.logger.error('Login failed:', {
        error: error.message,
        stack: error.stack,
        body: {
          username: loginDto.username,
          email: loginDto.email,
          hasPassword: !!loginDto.password,
        },
      });
      throw new UnauthorizedException('Invalid email or password');
    }
  }

  @Post('register')
  async register(@Body() createUserDto: CreateUserDto) {
    console.log('=== Registration endpoint hit ===');
    this.logger.log('=== Registration endpoint hit ===');
    console.log('Registration request received:', createUserDto);
    this.logger.log('Registration request received:', {
      email: createUserDto.email,
      name: createUserDto.name,
      hasPassword: !!createUserDto.password
    });

    try {
      console.log('Calling AuthService.createUser...');
      this.logger.log('Calling AuthService.createUser...');
      const result = await this.authService.createUser(createUserDto);
      console.log('Registration successful:', result);
      this.logger.log('Registration successful:', {
        id: result.id,
        email: result.email,
        name: result.name,
      });
      return result;
    } catch (error) {
      console.error('Registration failed:', error);
      this.logger.error('Registration failed:', {
        error: error.message,
        code: error.code,
        command: error.command,
        stack: error.stack,
      });
      throw error;
    }
  }

  //@UseGuards(JwtAuthGuard)
  @Post('create-admin')
  async createAdmin(@Body() createUserDto: CreateUserDto) {
    this.logger.log('=== Create admin endpoint hit ===');
    this.logger.debug('Admin creation request received:', {
      email: createUserDto.email,
      name: createUserDto.name,
    });

    try {
      this.logger.debug('Calling AuthService.createUser with isAdmin=true...');
      const result = await this.authService.createUser(createUserDto, true);
      this.logger.debug('Admin creation successful:', {
        id: result.id,
        email: result.email,
        name: result.name,
      });
      return result;
    } catch (error) {
      this.logger.error('Admin creation failed:', {
        error: error.message,
        stack: error.stack,
      });
      throw error;
    }
  }

  @UseGuards(JwtAuthGuard)
  @Get('user-info')
  async getUserInfo(@Request() req) {
    return this.authService.getUserInfo(req.user.userId);
  }

  @Post('forgot-password')
  async forgotPassword(@Body() { email }: { email: string }) {
    if (!email) {
      throw new BadRequestException('Email is required');
    }
    return this.authService.sendPasswordResetToken(email);
  }

  @Post('reset-password')
  async resetPassword(
    @Body() { token, newPassword }: { token: string; newPassword: string }
  ) {
    if (!token || !newPassword) {
      throw new BadRequestException('Token and new password are required');
    }
    if (newPassword.length < 6) {
      throw new BadRequestException('Password must be at least 6 characters long');
    }
    return this.authService.resetPasswordWithToken(token, newPassword);
  }
}
