import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { ForbiddenException, Injectable, UnauthorizedException } from '@nestjs/common';
import { ContextIdFactory, ModuleRef } from '@nestjs/core';
import { AuthService } from '../auth.service';
import { UsersService } from 'src/users/users.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private moduleRef: ModuleRef) {
    super({
      passReqToCallback: true,
    });
  }

  async validate(
    req: Express.Request,
    username: string,
    password: string,
  ) {
    // console.log('Triggered local.strategy.ts')
    const contextId = ContextIdFactory.getByRequest(req);
    // "AuthService" is a request-scoped provider
    // https://docs.nestjs.com/recipes/passport#request-scoped-strategies
    const authService = await this.moduleRef.resolve(AuthService, contextId);
    let user = await authService.validateUser(username, password);
    if (!user) throw new UnauthorizedException('INVALID_CREDENTIALS');
    if (user.status === 0) throw new ForbiddenException();
    const userService = await this.moduleRef.resolve(UsersService, contextId);
    user = await userService.findByIdWithRoles(user.user_id);
    return user;
  }
}