import { Injectable } from '@nestjs/common';
import { BaseIndexManager } from 'src/core/modules/domain/usecase/managers/base-index.manager';
import { UserEntity } from '../../entities/user.entity';
import { SelectQueryBuilder } from 'typeorm';
import {
  Param,
  RelationParam,
} from 'src/core/modules/domain/entities/base-filter.entity';
import { UserRole } from '../../../constants';

@Injectable()
export class IndexUserManager extends BaseIndexManager<UserEntity> {
  async prepareData(): Promise<void> {
    return;
  }

  async beforeProcess(): Promise<void> {
    return;
  }

  async afterProcess(): Promise<void> {
    return;
  }

  get relations(): RelationParam {
    return {
      // relation only join (for query purpose)
      joinRelations: [],

      // relation join and select (relasi yang ingin ditampilkan),
      selectRelations: ['user_privilege', 'user_login'],

      // relation yang hanya ingin dihitung (akan return number)
      countRelations: [],
    };
  }

  get selects(): string[] {
    return [
      `${this.tableName}.id`,
      `${this.tableName}.status`,
      `${this.tableName}.name`,
      `${this.tableName}.username`,
      `${this.tableName}.role`,
      `${this.tableName}.created_at`,
      `${this.tableName}.creator_name`,
      `${this.tableName}.updated_at`,
      `${this.tableName}.editor_name`,

      'user_privilege.id',
      'user_privilege.name',

      'user_login.id',
      'user_login.login_date',
      'user_login.item_id',
      'user_login.item_name',
      'user_login.source',
    ];
  }

  get specificFilter(): Param[] {
    return [
      {
        cols: `${this.tableName}.name`,
        data: this.filterParam.names,
      },
      {
        cols: `${this.tableName}.username`,
        data: this.filterParam.usernames,
      },
      {
        cols: `user_privilege.name`,
        data: this.filterParam.user_privileges,
      },
    ];
  }

  setQueryFilter(
    queryBuilder: SelectQueryBuilder<UserEntity>,
  ): SelectQueryBuilder<UserEntity> {
    // jangan tampilkan role tenant
    // ? karena menggunakan table user (admin, staff, tenant)
    queryBuilder.andWhere(`${this.tableName}.role != :tenant`, {
      tenant: UserRole.TENANT,
    });

    return queryBuilder;
  }
}
