import {
  HttpStatus,
  Injectable,
  Scope,
  UnauthorizedException,
} from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import {
  CONNECTION_NAME,
  OPERATION,
} from 'src/core/strings/constants/base.constants';
import { DataSource } from 'typeorm';
import { UserRole } from 'src/modules/user-related/user/constants';
import { UserModel } from 'src/modules/user-related/user/data/models/user.model';
import { AppSource, LogUserType } from 'src/core/helpers/constant';
import { EventBus } from '@nestjs/cqrs';
import { LogUserLoginEvent } from 'src/modules/configuration/log/domain/entities/log-user-login.event';
import { UserLoginModel } from 'src/modules/user-related/user/data/models/user-login.model';

interface UserEntity {
  user_id: string;
  username: string;
  role: UserRole;
  user_privilege_id: string;
  item_id: string;
  item_name: string;
  source: AppSource;
}

@Injectable({ scope: Scope.REQUEST })
export class AuthService {
  constructor(
    @InjectDataSource(CONNECTION_NAME.DEFAULT)
    protected readonly dataSource: DataSource,

    private eventBus: EventBus,
  ) {}

  get repository() {
    return this.dataSource.getRepository(UserLoginModel);
  }

  async logoutUser(user: UserEntity, token: string) {
    await this.repository.delete({ login_token: token });

    const userLogout = {
      type: LogUserType.logout,
      created_at: new Date().getTime(),
      name: user.username,
      user_privilege_id: user.user_privilege_id,
      ...user,
    };

    this.eventBus.publish(
      new LogUserLoginEvent({
        id: user.user_id,
        old: null,
        data: userLogout,
        user: userLogout as any,
        description: 'Logout',
        module: UserModel.name,
        op: OPERATION.UPDATE,
      }),
    );
  }

  async verifyRegisteredLoginToken(token: string) {
    const data = await this.repository.findOneBy({ login_token: token });

    if (!data) {
      throw new UnauthorizedException({
        statusCode: HttpStatus.UNAUTHORIZED,
        message: `Invalid token`,
        error: 'Unauthorized',
      });
    }
  }
}
