import { ref } from 'vue'
import { useConfigStore } from '@/stores/config'
import { DEFAULT_FLEET } from '@/mock/data/configs'
import type { FleetGroup, FleetLifecycleConfig } from '@/types/config'

const groups = ref<FleetGroup[]>([])
const loading = ref(false)

/** 共享车队分组配置（运维总览分配 + 筛选联动） */
export function useFleetGroups() {
  const store = useConfigStore()

  async function reload(force = false) {
    loading.value = true
    try {
      const env = await store.load<FleetLifecycleConfig>('fleet', force)
      const payload = env.payload ?? DEFAULT_FLEET
      groups.value = JSON.parse(JSON.stringify(payload.groups ?? [])) as FleetGroup[]
    } finally {
      loading.value = false
    }
  }

  function fleetNameForCarId(carId: string): string | undefined {
    for (const g of groups.value) {
      if (g.carIds.includes(carId)) return g.name || g.id
    }
    return undefined
  }

  function regionForCarId(carId: string): string | undefined {
    for (const g of groups.value) {
      if (g.carIds.includes(carId)) return g.region || undefined
    }
    return undefined
  }

  return { groups, loading, reload, fleetNameForCarId, regionForCarId }
}
