import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { InjectModel } from 'nest-knexjs';
import { Knex } from 'knex';
import { createHash } from 'crypto';

@Injectable()
export class AuthService {
  constructor(
    @InjectModel() private readonly knex: Knex,
    private jwt: JwtService,
    private config: ConfigService,
  ) {}

  async login(dto: { username: string; password: string }) {
    const password = createHash('sha512')
      .update(dto.password + this.config.get('PWD_ENCRYPTION_KEY'))
      .digest('hex');

    const user = await this.knex('tbl_users')
      .where({
        username: dto.username,
        password: password,
      })
      .first();

    if (!user) {
      throw new UnauthorizedException('Invalid credentials');
    }

    return this.signToken(user.id, user.username);
  }

  async signToken(userid: number, username: string) {
    const payload = {
      userid: userid,
      username: username,
    };
    const token = this.jwt.sign(payload, {
      expiresIn: '1h',
      secret: this.config.get('JWT_SECRET'),
    });
    return { access_token: token };
  }
}
