import type { ReportTestDetails } from '@/utils/reportTestDetails'
import { request, type ApiResponse } from './request'
import type { PersistedTestRecord, TestConsoleDetail } from './tests'
import type { ReportMetricKey } from '@/utils/reportMeasurementChart'

export interface FormationSelection { testId: number; testBatteryId: number }
export interface FormationCandidate { selection: FormationSelection; name: string; type: string; groupId: number; batteryGroup: string; batteryNo: string; consoleDetail?: TestConsoleDetail | null }
export interface FormationField { key: string; scope: 'detail' | 'cycle'; kind: 'battery' | 'metric' | 'manual' | 'calculated'; displayName: string; unit: string; fieldDefinitionId?: number | null }
export interface FormationChargeStep { stepNo: number; name: string; stepType: string; endVoltage: number | null; capacity?: number | null; direction?: 'CHARGE' | 'DISCHARGE' | 'REST' | 'UNKNOWN' }
export interface FormationItem {
  source: FormationCandidate
  cycleNos: number[]
  cycles: Array<Record<string, unknown>>
  metrics: Record<string, Record<string, number | null>>
  businessFields: Array<{ fieldDefinitionId: number; fieldName: string; fieldValue: string | null }>
  chargeSteps: Record<string, FormationChargeStep[]>
  curves?: Record<string, { zeroTime: number | null; records: PersistedTestRecord[] }>
  stepCurves?: Record<string, Record<string, { zeroTime: number | null; records: PersistedTestRecord[] }>>
}
export interface FormationMatrix { items: FormationItem[]; cycleNos: number[] }
export interface FormationStepSelection { charge: number[]; discharge: number[] }
export interface FormationSettings { fields: FormationField[]; values: Record<string, string>; chargeStepSelections: Record<string, number>; metrics?: ReportMetricKey[]; seriesColors?: Record<string, string>; manualChargeSteps?: Record<string, number[]>; curveStepSelections?: Record<string, FormationStepSelection>; hiddenSeriesKeys?: string[]; activeCycle?: number | null; sourceDetailOverrides?: ReportTestDetails }
export interface FormationSummary { id: number; name: string; creator: string; createdAt: number; testName?: string; batteryGroup?: string; versionNo: number }
export interface FormationVersion { versionNo: number; operatorName: string; createdAt: number; changeSummary: string }
export interface SavedFormationReport extends FormationSummary, FormationMatrix {
  curvesDeferred?: boolean
  description: string; settings: FormationSettings; versionNo: number; operatorName: string; versionCreatedAt: number; changeSummary: string
  units: Record<string, string>; displayUnits: Record<string, string>
  curveMode?: 'actual-steps'
  calculatedValues: Record<string, number | null>
}
export interface FormationCycleCurve { selection: FormationSelection; curve: { zeroTime: number | null; records: PersistedTestRecord[] } | null }
export interface FormationTemplate { id: number; name: string; type: 'formation'; fields: FormationField[]; creator: string; updatedAt: number }
export interface CreateFormationReport { name: string; description: string; selections: FormationSelection[]; settings: FormationSettings }

const root = '/system/formation-report'
async function data<T>(path: string, method = 'GET', body?: unknown) {
  return (await request<ApiResponse & { data: T }>(`${root}${path}`, { method, ...(body === undefined ? {} : { body: JSON.stringify(body) }) })).data
}
/** 列表来自后端身份记录，前端只负责筛选和分页。 */
export async function listFormationReports() { return (await request<ApiResponse & { rows: FormationSummary[] }>(`${root}/list`)).rows }
export function getFormationSources() { return data<FormationCandidate[]>('/sources') }
export function previewFormationReport(selections: FormationSelection[]) { return data<FormationMatrix>('/preview', 'POST', selections) }
/** 首次保存发送身份与展示值，测量由后端冻结。 */
export function createFormationReport(body: CreateFormationReport) { return data<SavedFormationReport>('', 'POST', body) }
export function getFormationReport(id: number, version?: number, editing = false) {
  return data<SavedFormationReport>(`/${id}${editing ? '/editing' : version === undefined ? '' : `/versions/${version}`}`)
}
/** 只加载首屏固定版本的当前循环；编辑与查看保留独立权限入口。 */
export async function getFormationCycleCurves(id: number, version: number, cycle: number, editing = false, signal?: AbortSignal) {
  return (await request<ApiResponse & { data: FormationCycleCurve[] }>(`${root}/${id}${editing ? '/editing' : ''}/versions/${version}/cycles/${cycle}`, {signal})).data
}
export function editFormationReport(id: number, body: Omit<CreateFormationReport, 'selections'> & { baseVersionNo: number; changeSummary: string }) {
  return data<SavedFormationReport>(`/${id}/versions`, 'POST', body)
}
export function refreshFormationSource(id: number, baseVersionNo: number, changeSummary: string) {
  return data<SavedFormationReport>(`/${id}/refresh-source`, 'POST', { baseVersionNo, changeSummary })
}
export function listFormationVersions(id: number) { return data<FormationVersion[]>(`/${id}/versions`) }
export function deleteFormationReport(id: number) { return data<void>(`/${id}`, 'DELETE') }
/** 导出动作独立授权，只读取指定已保存版本。 */
export function getFormationPrintVersion(id: number, versionNo: number) { return data<SavedFormationReport>(`/${id}/versions/${versionNo}/print`) }
export function listFormationTemplates() { return data<FormationTemplate[]>('/templates') }
export function createFormationTemplate(name: string, fields: FormationField[]) { return data<number>('/templates', 'POST', { name, fields }) }
export function updateFormationTemplate(id: number, name: string, fields: FormationField[]) { return data<void>(`/templates/${id}`, 'PUT', { name, fields }) }

/** 相同电池号跨测试仍为独立列，详情字段使用循环零占位而非虚构循环。 */
export function formationValueKey(item: FormationItem, cycle: number, field: FormationField) {
  return `${item.source.selection.testId}|${item.source.selection.testBatteryId}|${cycle}|${field.key}`
}
