import type { APIError, PlanResponse, TravelPreferences } from '@/types/travel'

// H5 dev uses the Vite /api proxy; mini-program builds should inject an HTTPS base URL.
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || ''

const request = <T>(options: UniApp.RequestOptions): Promise<T> =>
  new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success: (response) => {
        if (response.statusCode >= 200 && response.statusCode < 300) {
          resolve(response.data as T)
          return
        }
        const error = response.data as APIError
        reject(new Error(error?.detail || `请求失败（${response.statusCode}）`))
      },
      fail: () => {
        reject(new Error('无法连接行程服务，请检查后端是否已启动'))
      },
    })
  })

export const createPlan = (preferences: TravelPreferences) =>
  request<PlanResponse>({
    url: `${API_BASE_URL}/api/v1/plans`,
    method: 'POST',
    data: preferences,
    header: { 'content-type': 'application/json' },
    timeout: 50000,
  })

export const adjustPlan = (conversationId: string, message: string) =>
  request<PlanResponse>({
    url: `${API_BASE_URL}/api/v1/conversations/${conversationId}/messages`,
    method: 'POST',
    data: { message },
    header: { 'content-type': 'application/json' },
    timeout: 50000,
  })

export const PLAN_STORAGE_KEY = 'guangming:last-plan'
export const PREFERENCES_STORAGE_KEY = 'guangming:last-preferences'

export const savePlan = (plan: PlanResponse) => {
  uni.setStorageSync(PLAN_STORAGE_KEY, plan)
}

export const loadPlan = (): PlanResponse | null => {
  const value = uni.getStorageSync(PLAN_STORAGE_KEY)
  return value && typeof value === 'object' ? (value as PlanResponse) : null
}

export const savePreferences = (preferences: TravelPreferences) => {
  uni.setStorageSync(PREFERENCES_STORAGE_KEY, preferences)
}

export const loadPreferences = (): TravelPreferences | null => {
  const value = uni.getStorageSync(PREFERENCES_STORAGE_KEY)
  return value && typeof value === 'object' ? (value as TravelPreferences) : null
}
