import http from './http'

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

export interface SignalColumn {
  key: string
  label: string
  type: 'string' | 'int' | 'bool' | 'enum' | string
  options?: string[] | null
  group?: string | null
}

export interface SignalTableSummary {
  id: string
  title: string
  category: string
  fileName: string
}

export interface SignalTableDto extends SignalTableSummary {
  exists: boolean
  error?: string | null
  columns: SignalColumn[]
  rows: Record<string, unknown>[]
}

export interface SignalDataListDto {
  signalEnabled: boolean
  workingDirectory?: string | null
  tables: SignalTableSummary[]
}

export async function listSignalTables(): Promise<SignalDataListDto> {
  if (MOCK) {
    return {
      signalEnabled: true,
      workingDirectory: 'D:\\工作\\stand\\Simple3',
      tables: [
        { id: 'stations', title: 'PLC机构', category: 'PLC数据管理', fileName: 'stations.json' },
        { id: 'docks', title: '机构工位', category: 'PLC数据管理', fileName: 'station-docks.json' },
        { id: 'handshake', title: '握手点', category: '握手点数据管理', fileName: 'handshake-points.json' },
        { id: 'release', title: '放行点', category: '放行点数据管理', fileName: 'release-points.json' },
        { id: 'mag-control', title: '磁条管控区', category: '磁条交管', fileName: 'mag-control-areas.json' }
      ]
    }
  }
  const { data } = await http.get<SignalDataListDto>('/signal-data', { params: { summary: true } })
  return data
}

export async function getSignalTable(id: string): Promise<SignalTableDto> {
  if (MOCK) {
    const list = await listSignalTables()
    const meta = list.tables.find((t) => t.id === id)
    if (!meta) throw new Error(`未知数据表：${id}`)
    return { ...meta, exists: true, columns: [], rows: [] }
  }
  const { data } = await http.get<SignalTableDto>(`/signal-data/${id}`)
  return data
}

export async function saveSignalTable(id: string, rows: Record<string, unknown>[]): Promise<SignalTableDto> {
  if (MOCK) {
    const t = await getSignalTable(id)
    return { ...t, rows: JSON.parse(JSON.stringify(rows)) }
  }
  const { data } = await http.put<SignalTableDto>(`/signal-data/${id}`, { rows })
  return data
}
