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 { DriverEntity } from '../../../entities/driver.entity';

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

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

  async findByIdWithRelations(id: string): Promise<DriverEntity | null> {
    const tenantId = this.getTenantId();
    return this.repo.findOne({
      where: { id, tenant_id: tenantId, is_deleted: false } as any,
      relations: ['destination', 'supplier'],
    });
  }

  async findBySupplier(supplierId: string): Promise<DriverEntity[]> {
    const tenantId = this.getTenantId();
    return this.repo.find({
      where: { supplier_id: supplierId, tenant_id: tenantId, is_deleted: false } as any,
      relations: ['destination', 'supplier'],
      order: { name: 'ASC' },
    });
  }

  async findByLicenseNo(licenseNo: string): Promise<DriverEntity | null> {
    const tenantId = this.getTenantId();
    return this.repo.findOne({
      where: { license_no: licenseNo, tenant_id: tenantId, is_deleted: false } as any,
    });
  }
}
