import { Controller, Request, Post, UseGuards, Body, Get, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
import { UserRole } from '../users/user.entity';
import { JwtAuthGuard } from './jwt-auth.guard';

@Controller('api/auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @Post('register')
  async register(@Body() body: any) {
    const { email, password, role, kyc_id_front, kyc_id_back, kyc_video_url, profile } = body;
    // Basic validation
    if (!email || !password || !role) {
      return { error: 'Email, password, and role are required' };
    }
    // Brand, creator, and manager MUST upload identity documents and video
    if (['creator', 'brand', 'manager'].includes(role) && (!kyc_id_front || !kyc_id_back || !kyc_video_url)) {
      return { error: 'Proof of identity (Front, Back, and Verification Video) is required for registration' };
    }
    return this.authService.register(email, password, role, kyc_id_front, kyc_id_back, kyc_video_url, profile);
  }

  @Post('login')
  async login(@Body() body: any) {
    const { email, password } = body;
    const user = await this.authService.validateUser(email, password);
    if (!user) throw new UnauthorizedException('Invalid credentials');
    if (user.blocked_reason === 'PENDING_VERIFICATION') throw new UnauthorizedException('Account pending verification');
    if (user.blocked_reason === 'REJECTED') throw new UnauthorizedException('Account rejected');
    return this.authService.login(user);
  }

  @UseGuards(JwtAuthGuard)
  @Get('me')
  async getProfile(@Request() req: any) {
    const user = await this.authService['usersService'].findByIdWithProfiles(req.user.userId);
    const displayName =
      user?.creatorProfile?.full_name ||
      user?.managerProfile?.full_name ||
      user?.brandProfile?.company_name ||
      user?.brandProfile?.contact_person ||
      user?.email?.split('@')[0] ||
      'User';

    return {
      ...req.user,
      account_status: user?.account_status,
      display_name: displayName,
    };
  }

  @UseGuards(JwtAuthGuard)
  @Post('change-password')
  async changePassword(@Request() req: any, @Body() body: { currentPassword: string; newPassword: string }) {
    return this.authService.changePassword(req.user.userId, body.currentPassword, body.newPassword);
  }

  @UseGuards(JwtAuthGuard)
  @Post('change-email')
  async changeEmail(@Request() req: any, @Body() body: { newEmail: string; currentPassword: string }) {
    return this.authService.changeEmail(req.user.userId, body.newEmail, body.currentPassword);
  }
}
