import vehicles from '../../vehicle-management/data/vehicles.json';
import { getVehicleRef, isPlateInVehicleSystem as isPlateInLeaseRegistry } from '../../lease-business-detail/utils/system-ref';

type VehicleSeed = { plateNo?: string; brand?: string; model?: string };

/** 物流业务明细样例车牌（与车辆主数据 / 运营台账对齐） */
const SEED_PLATE_MAP: Record<string, { brand: string; model: string }> = {
  粤AGQ8393: { brand: '现代', model: '帕力安牌4.5吨冷链车' },
  粤AGR3208: { brand: '现代', model: '帕力安牌4.5吨冷链车' },
  粤AGP6680: { brand: '现代', model: '帕力安牌4.5吨冷链车' },
  粤AGP9835: { brand: '现代', model: '帕力安牌4.5吨冷链车' },
  粤AGP9825: { brand: '现代', model: '帕力安牌4.5吨冷链车' },
  粤AGP9331: { brand: '现代', model: '帕力安牌4.5吨冷链车' },
  粤AGP6651: { brand: '现代', model: '帕力安牌4.5吨冷链车' },
  粤AGP6639: { brand: '现代', model: '帕力安牌4.5吨冷链车' },
};

const plateFromVehicles = new Map<string, { brand: string; model: string }>();
(vehicles as VehicleSeed[]).forEach((vehicle) => {
  if (!vehicle.plateNo) return;
  plateFromVehicles.set(vehicle.plateNo.trim(), {
    brand: vehicle.brand ?? '',
    model: vehicle.model ?? '',
  });
});

export function formatBrandModelDot(brand: string, model: string): string {
  if (brand && model) return `${brand}·${model}`;
  return brand || model || '';
}

/** 根据车牌从车辆主数据解析系统车型：品牌·型号 */
export function resolveSystemVehicleType(plateNo: string): string {
  const plate = plateNo.trim();
  if (!plate) return '';

  const leaseRef = getVehicleRef(plate);
  if (leaseRef?.brandModel) return leaseRef.brandModel;
  if (leaseRef?.brand || leaseRef?.model) {
    return formatBrandModelDot(leaseRef.brand, leaseRef.model);
  }

  const fromRegistry = plateFromVehicles.get(plate);
  if (fromRegistry) return formatBrandModelDot(fromRegistry.brand, fromRegistry.model);

  const seed = SEED_PLATE_MAP[plate];
  if (seed) return formatBrandModelDot(seed.brand, seed.model);

  return '';
}

export function isPlateInVehicleSystem(plateNo: string): boolean {
  const plate = plateNo.trim();
  if (!plate) return false;
  return isPlateInLeaseRegistry(plate)
    || plateFromVehicles.has(plate)
    || Boolean(SEED_PLATE_MAP[plate]);
}
