import { Injectable } from '@nestjs/common';
import { DataSource, FindManyOptions, Repository } from 'typeorm';
import { Yard } from '../entities/yard.entity';
import { IYardsRepository } from '../interfaces/yards.repository.interface';

@Injectable()
export class YardsRepository implements IYardsRepository {
  private readonly repo: Repository<Yard>;

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

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

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

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

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

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

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

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