import { Container } from 'typedi';
import { Connection, Repository } from 'typeorm';
import { Body } from '../../../src/decorator/body.decorator';
import { ClassBasedView } from '../../../src/decorator/classBasedView.decorator';
import { OnInit } from '../../../src/interface/view/onInit.interface';
import { HashUtils } from '../../../src/util/encryption/bcrypt.encryption';
import { AdminMetadata } from '../src/metadata/admin.metadata';

@ClassBasedView({
  asJson: true,
  method: 'POST',
  route: '/admin/api/v1/auth/login',
})
export class ApiLoginView implements OnInit {
  public result: any = {};

  public constructor() {
    try {
      this._connection = AdminMetadata.connection;
    } catch (e) {
      this.result.error = e.message;
    }
  }

  public async onInit(): Promise<any> {
    await this.getUserTokenForCookie();
    return this.result;
  }

  public async getUserTokenForCookie(): Promise<void> {
    const repository: Repository<any> = this._connection.getRepository(AdminMetadata.validationEntity);
    const user = await repository.findOne({ email: this._body.email });

    if (!user) {
      this.result.error = 'Incorrect credentials';
      return;
    }

    if (!Container.get(HashUtils).validate(this._body.password, user.password)) {
      this.result.error = 'Incorrect credentials';
      return;
    }

    this.result.token = user.token;
  }
}
  @Body()
  private _body: any;

  private _connection: Connection;
