import { Injectable } from '@nestjs/common';
import { DataSource, FindManyOptions, Repository } from 'typeorm';
import { WeightLimitRule } from '../entities/weight-limit-rule.entity';
import { IWeightLimitRulesRepository } from '../interfaces/weight-limit-rules.repository.interface';

@Injectable()
export class WeightLimitRulesRepository implements IWeightLimitRulesRepository {
  private readonly repo: Repository<WeightLimitRule>;

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

  findById(id: string): Promise<WeightLimitRule | null> {
    return this.repo.findOne({
      where: { id },
      relations: { containerType: true },
    });
  }

  findActiveByContainerTypeId(
    containerTypeId: string,
    tradeDirection: string,
  ): Promise<WeightLimitRule[]> {
    const now = new Date();
    return this.repo
      .createQueryBuilder('rule')
      .innerJoinAndSelect('rule.containerType', 'ct')
      .where('rule.container_type_id = :containerTypeId', { containerTypeId })
      .andWhere('(rule.trade_direction = :dir OR rule.trade_direction = :both)', {
        dir: tradeDirection,
        both: 'BOTH',
      })
      .andWhere('rule.effective_from <= :now', { now })
      .andWhere('(rule.effective_to IS NULL OR rule.effective_to > :now)', { now })
      .getMany();
  }

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

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

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

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

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