import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
import { AuthService } from 'modules/auth/auth.service';
import { UserResponseDto } from 'modules/user/dto/user-response.dto';
import { UserRole } from 'common/enum/UserRole.enum';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  private logger = new Logger('LocalStrategy');
  constructor(private authService: AuthService) {
    super({ usernameField: 'email' });
  }

  async validate(email: string, password: string, role: UserRole): Promise<any> {
    this.logger.debug(`Validating user with email: ${email}`);
    const user: UserResponseDto = await this.authService.validateUser(email, password, [role]);
    if (!user) {
      throw new UnauthorizedException('Invalid credentials');
    }
    this.logger.debug(`User validated: ${JSON.stringify(user)}`);
    return user;
  }
}
