import { Injectable } from '@nestjs/common';
import { DataSource, FindManyOptions, Repository } from 'typeorm';
import { PriorityConfig } from '../entities/priority-config.entity';
import { IPriorityConfigsRepository } from '../interfaces/priority-configs.repository.interface';

@Injectable()
export class PriorityConfigsRepository implements IPriorityConfigsRepository {
  private readonly repo: Repository<PriorityConfig>;

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

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

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

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

  async findAllActive(): Promise<PriorityConfig[]> {
    return this.repo.find({
      where: { isActive: true },
      order: { displayOrder: 'ASC' },
    });
  }

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

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

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