import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ClsService } from 'nestjs-cls';
import { TenantAwareRepository } from '../../../common/repositories/tenant-aware.repository';
import { SupplierEntity } from '../../../entities/supplier.entity';

@Injectable()
export class SupplierRepository extends TenantAwareRepository<SupplierEntity> {
  constructor(@InjectRepository(SupplierEntity) repo: Repository<SupplierEntity>, cls: ClsService) {
    super(repo, cls);
  }

  async findAllWithDestination(): Promise<SupplierEntity[]> {
    const tenantId = this.getTenantId();
    return this.repo.find({
      where: { tenant_id: tenantId, is_deleted: false },
      relations: {
        destination: true,
      },
      order: { name: 'ASC' },
    });
  }

  async findByIdWithDestination(id: string): Promise<SupplierEntity | null> {
    const tenantId = this.getTenantId();
    return this.repo.findOne({
      where: { id, tenant_id: tenantId, is_deleted: false },
      relations: {
        destination: true,
      },
    });
  }

  async findByNameAndDestination(
    name: string,
    destinationId: string,
  ): Promise<SupplierEntity | null> {
    const tenantId = this.getTenantId();
    return this.repo.findOne({
      where: { name, destination_id: destinationId, tenant_id: tenantId, is_deleted: false },
    });
  }
}
