import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ClsService } from 'nestjs-cls';
import { TenantAwareRepository } from '../../../common/repositories/tenant-aware.repository';
import { ExchangeRateEntity } from '../../../entities/exchange-rate.entity';

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

  async findAllWithCurrencies(): Promise<ExchangeRateEntity[]> {
    const tenantId = this.getTenantId();
    return this.repo.find({
      where: { tenant_id: tenantId, is_deleted: false } as any,
      relations: ['from_currency', 'to_currency'],
      order: { created_at: 'DESC' },
    });
  }

  async findPaginatedWithSearch(query: { page?: number; limit?: number; search?: string }) {
    const tenantId = this.getTenantId();
    const { page = 1, limit = 10, search } = query;
    const trimmed = search?.trim();

    const qb = this.repo.createQueryBuilder('er')
      .leftJoinAndSelect('er.from_currency', 'fc')
      .leftJoinAndSelect('er.to_currency', 'tc')
      .where('er.tenant_id = :tenantId', { tenantId })
      .andWhere('er.is_deleted = false');

    if (trimmed) {
      qb.andWhere('(fc.code ILIKE :search OR fc.name ILIKE :search OR tc.code ILIKE :search OR tc.name ILIKE :search)', { search: `%${trimmed}%` });
    }

    const total = await qb.getCount();
    const items = await qb
      .orderBy('er.created_at', 'DESC')
      .skip((page - 1) * limit)
      .take(limit)
      .getMany();

    return { items, meta: { total, page, limit, totalPages: Math.ceil(total / limit) } };
  }

  async findByPair(fromId: string, toId: string): Promise<ExchangeRateEntity | null> {
    const tenantId = this.getTenantId();
    return this.repo.findOne({
      where: { from_currency_id: fromId, to_currency_id: toId, tenant_id: tenantId, is_deleted: false } as any,
    });
  }
}
