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

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

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

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

  async findByVehicleNo(vehicleNo: string): Promise<VehicleEntity | null> {
    const tenantId = this.getTenantId();
    return this.repo.findOne({
      where: { vehicle_no: vehicleNo, tenant_id: tenantId, is_deleted: false },
    });
  }
}
