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

@Injectable()
export class ContainerTypesRepository implements IContainerTypesRepository {
  private readonly repo: Repository<ContainerType>;

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

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

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

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

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

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

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

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