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

@Injectable()
export class PriorityRulesRepository implements IPriorityRulesRepository {
  private readonly repo: Repository<PriorityRule>;

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

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

  findAllActive(): Promise<PriorityRule[]> {
    return this.repo.find({ where: { isActive: true } });
  }

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

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

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

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

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