import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
import { LoginDto } from './login-dto';
import { DateTime } from 'luxon';
import { User } from '../users/schemas/user.schema';

@Injectable()
export class AuthService {
  constructor(private usersService: UsersService, private jwtService: JwtService) {}

  async validateUser(loginDto: LoginDto): Promise<any> {
    const user = await this.usersService.findOne(loginDto.email);
    if (user) {
      return user;
    }
    return null;
  }

  async login(loginDto: LoginDto): Promise<{ username; name; surname; token }> {
    // find user in db
    const user: User = await this.usersService.findByLogin(loginDto);
    if (!user.emailVerified) {
      throw new HttpException('Invalid credentials', HttpStatus.UNAUTHORIZED);
    }

    // generate and sign token
    const token = this._createToken(user);

    return {
      username: user.email,
      name: user.name,
      surname: user.surname,
      ...token,
    };
  }

  private _createToken(user: User): any {
    const local = DateTime.local().setZone('Europe/Paris');
    return {
      accessToken: this.jwtService.sign({ email: user.email, role: user.role }),
      expiresAt: local.plus({ days: 1 }),
    };
  }
}