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 } as any,
      relations: ['destination', 'supplier', 'assigned_driver'],
      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 } as any,
      relations: ['destination', 'supplier', 'assigned_driver'],
    });
  }

  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 } as any,
    });
  }
}
