import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Constants } from '../../../common/constants';
import { responseMessages } from '../../../messages/response-messages';
import { Users, UserRoles } from "../../../entities/users.entity";


@Injectable()
export class BrandStrategy extends PassportStrategy(Strategy, 'brand') {
  constructor(
    @InjectRepository(Users)
    private Users: Repository<Users>,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: Constants.jwt_secret,
    });
  }

  async validate(payload: any)
  {
    const user_id = payload.sub;

    if (!user_id) {
        throw new HttpException(responseMessages.en.strategy.access_token_invalid, HttpStatus.UNAUTHORIZED);
    }

    const existsBrand = await this.Users.findOne({where:{
      id : user_id, role: UserRoles.BRAND
    }});

    if(!existsBrand){
        throw new HttpException(responseMessages.en.strategy.brand_not_valid, HttpStatus.UNAUTHORIZED);
    }

    if(existsBrand.is_active == false){
        throw new HttpException(responseMessages.en.strategy.brand_not_active, HttpStatus.UNAUTHORIZED);
    }

    return existsBrand;
  }
}