import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import {
  FilterOperator,
  FilterSuffix,
  paginate,
  PaginateQuery,
} from 'nestjs-paginate';
import { Column } from 'nestjs-paginate/lib/helper';
import AppResponse from '@/response/app-response';
import Permission from '../entities/permission.entity';

@Injectable()
export class PermissionService {
  constructor(
    @InjectRepository(Permission)
    readonly permissionRepo: Repository<Permission>,
  ) {}

  async getPermissionsByAdmin(adminId: number): Promise<Permission[]> {
    return await this.permissionRepo
      .createQueryBuilder('permission')
      .innerJoin('permission.admins', 'admin')
      .where('admin.id = :adminId', { adminId })
      .getMany();
  }

  async index(query: PaginateQuery) {
    const filterableColumns: {
      [key in Column<Permission> | (string & {})]?:
        | (FilterOperator | FilterSuffix)[]
        | true;
    } = {
      id: true,
      created_at: true,
      updated_at: true,
    };

    query.filter = AppResponse.processFilters(query.filter, filterableColumns);

    const data = await paginate(query, this.permissionRepo, {
      sortableColumns: ['id'],
      searchableColumns: ['id'],
      defaultLimit: 15,
      filterableColumns,
      defaultSortBy: [['id', 'DESC']],
      maxLimit: 100,
    });

    return AppResponse.toPagination<Permission>(data, true, Permission);
  }
}
