import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, type FindOptionsWhere } from 'typeorm';
import { ClsService } from 'nestjs-cls';
import { TenantAwareRepository } from '../../../common/repositories/tenant-aware.repository';
import { BankEntity } from '../../../entities/bank.entity';

@Injectable()
export class BankRepository extends TenantAwareRepository<BankEntity> {
  constructor(@InjectRepository(BankEntity) repo: Repository<BankEntity>, cls: ClsService) {
    super(repo, cls);
  }

  async findAllActive(): Promise<BankEntity[]> {
    return this.find({
      where: { is_active: true } as FindOptionsWhere<BankEntity>,
      order: { name: 'ASC' },
    });
  }

  async findByName(name: string): Promise<BankEntity | null> {
    const tenantId = this.getTenantId();
    return this.repo
      .createQueryBuilder('b')
      .where('b.tenant_id = :tenantId', { tenantId })
      .andWhere('b.is_deleted = false')
      .andWhere('LOWER(b.name) = LOWER(:name)', { name: name.trim() })
      .getOne();
  }

  async countAccounts(bankId: string): Promise<number> {
    const tenantId = this.getTenantId();
    const rows = (await this.repo.manager.query(
      `SELECT COUNT(*)::int AS count
       FROM bank_accounts
       WHERE tenant_id = $1 AND bank_id = $2 AND is_deleted = false`,
      [tenantId, bankId],
    )) as Array<{ count: number }>;
    return rows[0]?.count ?? 0;
  }
}
