import http from './http'
import type { CreateDeliveryPayload, DeliveryTask } from '@/types/delivery'

const MOCK = import.meta.env.VITE_USE_MOCK === 'true'

const BASE = '/sl/projection/deliveries'

export async function listDeliveries(opts?: {
  includeFinished?: boolean
  includeAborted?: boolean
}): Promise<DeliveryTask[]> {
  if (MOCK) {
    const { mockDeliveries } = await import('@/mock/data/deliveries')
    return mockDeliveries()
  }
  const params: Record<string, string> = {}
  if (opts?.includeFinished === false) params.includeFinished = 'false'
  if (opts?.includeAborted === false) params.includeAborted = 'false'
  const { data } = await http.get<DeliveryTask[]>(BASE, { params })
  return Array.isArray(data) ? data : []
}

/** CDM 任务快照订阅结果：来自平台库 cdm_tasks（SimpleLite 关闭时仍可读，含完整历史）。 */
export interface CdmTaskFeed {
  online: boolean
  lastSyncAt: string | null
  tasks: DeliveryTask[]
}

/**
 * 任务页数据源：优先读平台快照库 /fleet/tasks（离线可读 + 历史保留）；
 * 若平台端点不可用则回退到实时投影 /sl/projection/deliveries。
 */
export async function fetchCdmTaskFeed(limit = 1000): Promise<CdmTaskFeed> {
  if (MOCK) {
    const { mockDeliveries } = await import('@/mock/data/deliveries')
    return { online: true, lastSyncAt: new Date().toISOString(), tasks: await mockDeliveries() }
  }
  try {
    const { data } = await http.get<CdmTaskFeed>('/fleet/tasks', { params: { limit } })
    return {
      online: !!data?.online,
      lastSyncAt: data?.lastSyncAt ?? null,
      tasks: Array.isArray(data?.tasks) ? data.tasks : []
    }
  } catch {
    const tasks = await listDeliveries({ includeFinished: true, includeAborted: true })
    return { online: true, lastSyncAt: new Date().toISOString(), tasks }
  }
}

export async function cancelDelivery(id: string): Promise<void> {
  if (MOCK) return
  await http.post(`${BASE}/${encodeURIComponent(id)}/cancel`)
}

export async function resendDelivery(id: string): Promise<void> {
  if (MOCK) return
  await http.post(`${BASE}/${encodeURIComponent(id)}/resend`)
}

export async function forceCompleteDelivery(id: string): Promise<void> {
  if (MOCK) return
  await http.post(`${BASE}/${encodeURIComponent(id)}/force-complete`)
}

export async function pauseDelivery(id: string): Promise<void> {
  if (MOCK) return
  await http.post(`${BASE}/${encodeURIComponent(id)}/pause`)
}

export async function resumeDelivery(id: string): Promise<void> {
  if (MOCK) return
  await http.post(`${BASE}/${encodeURIComponent(id)}/resume`)
}

export async function changeCarDelivery(id: string): Promise<void> {
  if (MOCK) return
  await http.post(`${BASE}/${encodeURIComponent(id)}/change-car`)
}

export async function setDeliveryPriority(id: string, value: number): Promise<void> {
  if (MOCK) return
  await http.post(`${BASE}/${encodeURIComponent(id)}/priority`, { value })
}

export async function createDelivery(payload: CreateDeliveryPayload): Promise<{ id: string }> {
  if (MOCK) return { id: `MOCK-${Date.now()}` }
  const { data } = await http.post<{ success: boolean; id: string }>(BASE, payload)
  return { id: data?.id ?? '' }
}
