import { Injectable } from '@nestjs/common';
import { DataSource, FindManyOptions, Repository } from 'typeorm';
import { ServiceType } from '../entities/service-type.entity';
import { IServiceTypesRepository } from '../interfaces/service-types.repository.interface';

@Injectable()
export class ServiceTypesRepository implements IServiceTypesRepository {
  private readonly repo: Repository<ServiceType>;

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

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

  findByCode(code: string): Promise<ServiceType | null> {
    return this.repo.findOne({ where: { code } });
  }

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

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

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

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

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