import { Injectable } from '@nestjs/common';
import { DataSource, FindManyOptions, Repository } from 'typeorm';
import { Rate } from '../entities/rate.entity';
import { IRatesRepository } from '../interfaces/rates.repository.interface';

@Injectable()
export class RatesRepository implements IRatesRepository {
  private readonly repo: Repository<Rate>;

  constructor(private readonly dataSource: DataSource) {
    this.repo = this.dataSource.getRepository(Rate);
  }

  findById(id: string): Promise<Rate | null> {
    return this.repo.findOne({ where: { id } });
  }

  findLiveRates(): Promise<Rate[]> {
    const now = new Date();
    return this.repo
      .createQueryBuilder('rate')
      .where('rate.status = :status', { status: 'LIVE' })
      .andWhere('rate.effective_from <= :now', { now })
      .andWhere('(rate.effective_to IS NULL OR rate.effective_to > :now)', { now })
      .getMany();
  }

  findAll(options?: FindManyOptions<Rate>): Promise<Rate[]> {
    return this.repo.find(options);
  }

  findAndCount(options?: FindManyOptions<Rate>): Promise<[Rate[], number]> {
    return this.repo.findAndCount(options);
  }

  async create(data: Partial<Rate>): Promise<Rate> {
    const entity = this.repo.create(data);
    return this.repo.save(entity);
  }

  async update(id: string, data: Partial<Rate>): Promise<Rate | null> {
    await this.repo.update(id, data);
    return this.findById(id);
  }

  async softDelete(id: string): Promise<void> {
    await this.repo.softDelete(id);
  }
}
