import { Injectable } from '@nestjs/common';
import { DataSource, FindManyOptions, Repository } from 'typeorm';
import { ShippingLine } from '../entities/shipping-line.entity';
import { IShippingLinesRepository } from '../interfaces/shipping-lines.repository.interface';

@Injectable()
export class ShippingLinesRepository implements IShippingLinesRepository {
  private readonly repo: Repository<ShippingLine>;

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

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

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

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

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

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

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

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