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

@Injectable()
export class CargoTypesRepository implements ICargoTypesRepository {
  private readonly repo: Repository<CargoType>;

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

  findById(id: string): Promise<CargoType | null> {
    return this.repo.findOne({ where: { id }, relations: { parent: true } });
  }

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

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

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

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

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

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