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

@Injectable()
export class SurchargeTypesRepository implements ISurchargeTypesRepository {
  private readonly repo: Repository<SurchargeType>;

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

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

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

  findAllActiveWithRate(): Promise<SurchargeType[]> {
    return this.repo.find({
      where: { isActive: true },
      relations: { rate: true },
    });
  }

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

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

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

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

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