import { Injectable } from '@nestjs/common';
import { DataSource, FindManyOptions, Repository } from 'typeorm';
import { ApprovalRule } from '../entities/approval-rule.entity';
import { IApprovalRulesRepository } from '../interfaces/approval-rules.repository.interface';

@Injectable()
export class ApprovalRulesRepository implements IApprovalRulesRepository {
  private readonly repo: Repository<ApprovalRule>;

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

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

  findChainForCargo(requiresDirectorApproval: boolean): Promise<ApprovalRule[]> {
    return this.repo.find({
      where: { requiresDirectorApproval },
      order: { stepOrder: 'ASC' },
    });
  }

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

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

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

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

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