import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { AdminService } from 'src/admin/admin.service';
import { JwtService } from '@nestjs/jwt';
import { EncryptionService } from '../encryption/encryption.service';
import { CreateAdminDto } from 'src/admin/dto/create-admin.dto';
import { LoginAdminDto } from 'src/auth/admin/dto/login-admin.dto';
import { JwtConstants } from 'src/constants/jwt.constants';
import { AdminSigninResDto } from './dto/admin-signin-res.dto';
import { Admin } from 'src/admin/entities/admin.entity';
import { ADMIN_ROLE } from 'src/enum/admin-role.enum';

@Injectable()
export class AuthAdminService {
  constructor(
    private adminService: AdminService,
    private jwtService: JwtService,
    private encryptionService: EncryptionService,
  ) {}

  async signUp(createAdminDto: CreateAdminDto): Promise<string> {
    const loginAdminDto: LoginAdminDto = {
      email: createAdminDto.email,
      password: createAdminDto.password,
    };
    const hashedPwd = await this.encryptionService.hashPassword(createAdminDto.password);
    createAdminDto.password = hashedPwd;
    await this.adminService.create(createAdminDto);

    const adminSigninResDto: AdminSigninResDto = await this.signIn(loginAdminDto);
    return adminSigninResDto.token;
  }

  async signIn(logInAdmin: LoginAdminDto): Promise<AdminSigninResDto> {
    const admin: Admin = await this.adminService.findOne(logInAdmin.email);
    const validPwd: boolean = await this.encryptionService.comparePassword(logInAdmin.password, admin.password);
    if (!validPwd) {
      throw new HttpException('Invalid credentials', HttpStatus.UNAUTHORIZED);
    }
    const accessToken = await this.jwtService.sign({ email: admin.email }, { secret: JwtConstants.SECRET });
    const adminSigninResDto: AdminSigninResDto = {
      email: admin.email,
      name: admin.name,
      role: admin.role as ADMIN_ROLE,
      token: accessToken,
    };
    return adminSigninResDto;
  }
}
