import {
  HttpException,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { AuthValidationService } from '../services/auth-validation.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authDbService: AuthValidationService) {
    super({
      usernameField: 'Email',
      passwordField: 'Password',
    });
  }

  async validate(Email: string, Password: string) {
    try {
      const user = await this.authDbService.validateUserCredintials(
        Email,
        Password,
      );

      if (!user) {
        throw new UnauthorizedException();
      }

      return user;
    } catch (err) {
      const e = err as any;
      console.log('uh');
      console.log(err);

      let message = 'Invalid credentials';
      let statusCode = 401;
      if (e?.response?.message) {
        message = e.response.message;
      }

      if (e?.response?.statusCode) {
        statusCode = e.response.statusCode;
      }

      throw new HttpException(message, statusCode);
    }
  }
}
