import { Injectable, BadRequestException, UnauthorizedException, ForbiddenException } from '@nestjs/common';
import { CreateAuthenticationDto } from './dto/create-authentication.dto';
import { UtilisateursService } from '../utilisateurs/utilisateurs.service';
import * as bcrypt from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthenticationService {

  constructor(private utulisateurService: UtilisateursService, private jwtService: JwtService,){}

  async login(createAuthenticationDto: CreateAuthenticationDto): Promise<any> {
    try {
      
      const utilisateur: any = await this.utulisateurService.signin(createAuthenticationDto.email); 
     
      if (utilisateur.profil.code == 'partner' && utilisateur.updated_pwd == false) {
        if (utilisateur.tempPasswordExpiresAt && new Date() > utilisateur.tempPasswordExpiresAt) {
          throw new ForbiddenException('Votre mot de passe temporaire a expiré. Veuillez contacter le support.');
        }
      }  
     
      if (!utilisateur || !(await bcrypt.compare(createAuthenticationDto?.mot_de_passe, utilisateur?.mot_de_passe))) {
        throw new UnauthorizedException('Email ou mot de passe incorrect');
      }
      
      if (utilisateur.statut !== 'enable') {
        throw new UnauthorizedException('Votre compte à été désactivé, veuillez contacter l\'administrateur');
      }
     
      
      const payload = { userId: utilisateur.id, email: utilisateur.email };

      const access_token = this.jwtService.sign(payload, {secret: process.env.JWT_SECRET, expiresIn: process.env.JWT_TOKEN_EXPIRE,});
      delete utilisateur.mot_de_passe;
      return { utilisateur: utilisateur, access_token, token_type: 'bearer' , scope: "scope", expires_in: 3600   };

    } catch (error) {
      throw new BadRequestException(error.message);
    }
    
  }

  validateToken(token: string) {
    try {
      return this.jwtService.verify(token);
    } catch (error) {
      throw new UnauthorizedException('Token expiré ou invalide');
    }
  }

  
}
