import http from './http'
import type {
  WizardOptions,
  DeploymentProfileDto,
  SaveWizardRequest,
  EffectivePagesDto
} from '@/types/wizard'

// 与 api/auth.ts 一致：VITE_USE_MOCK==='true' 时走本地假数据，便于无后端联调。
const MOCK = import.meta.env.VITE_USE_MOCK === 'true'

const MOCK_OPTIONS: WizardOptions = {
  navigationKinds: [
    { id: 'magnetic', name: '磁导航', group: 'navigation', description: '磁条循迹 + 地标 / RFID 定位' },
    { id: 'qrcode', name: '二维码导航', group: 'navigation', description: '二维码地标 + 码值地图' },
    { id: 'laser', name: '激光导航', group: 'navigation', description: '反光板 / SLAM + 激光避障' }
  ],
  modules: [
    { id: 'wms', name: 'WMS 仓储管理', group: 'module', description: '库位 / 库存 / 出入库管理' },
    { id: 'ptl', name: 'PTL 拣选系统', group: 'module', description: 'Pick-to-Light 亮灯拣选与播种' }
  ],
  scenarios: {
    templates: [
      { id: 'tpl-sps', name: 'SPS 物料配送', category: 'SPS' },
      { id: 'tpl-pack', name: '电池 Pack 自动化产线', category: 'BatteryPack' },
      { id: 'tpl-loop', name: '环线运行', category: 'Loop' },
      { id: 'tpl-p2p', name: '点对点柔性搬运', category: 'P2P' }
    ]
  }
}

let mockProfile: DeploymentProfileDto = {
  configured: false,
  platformType: 'standard',
  modules: [],
  navigationKinds: [],
  scenarios: [],
  updatedBy: 'mock',
  activeSceneIds: [],
  hiddenPages: []
}

export async function getWizardOptions(): Promise<WizardOptions> {
  if (MOCK) return MOCK_OPTIONS
  const { data } = await http.get<WizardOptions>('/wizard/options')
  return data
}

export async function getWizardProfile(): Promise<DeploymentProfileDto> {
  if (MOCK) return mockProfile
  const { data } = await http.get<DeploymentProfileDto>('/wizard/profile')
  return data
}

export async function saveWizardProfile(req: SaveWizardRequest): Promise<DeploymentProfileDto> {
  if (MOCK) {
    mockProfile = {
      ...mockProfile,
      platformType: req.platformType ?? mockProfile.platformType,
      modules: req.modules ?? [],
      navigationKinds: req.navigationKinds ?? [],
      scenarios: req.scenarios ?? [],
      configured: true,
      activeSceneIds: (req.navigationKinds ?? []).map((k) => `scene.${k}`)
    }
    return mockProfile
  }
  const { data } = await http.put<DeploymentProfileDto>('/wizard/profile', req)
  return data
}

export async function getEffectivePages(): Promise<EffectivePagesDto> {
  if (MOCK) {
    return { configured: mockProfile.configured, tailorablePages: [], enabledPages: [], hiddenPages: [] }
  }
  const { data } = await http.get<EffectivePagesDto>('/wizard/effective-pages')
  return data
}
