import request from '@/utils/request'
import type {
  ScriptFlow,
  ScriptFlowDetail,
  ScriptFlowCreate,
  ScriptFlowUpdate,
  ScriptFlowListResponse
} from '@/types/script-flow'

export interface FlowSimulateRequest {
  userInputs: string[]
}

export interface FlowSimulateResponse {
  flowId: string
  flowName: string
  simulation: FlowSimulationStep[]
  result: {
    completed: boolean
    totalSteps: number
    totalDurationMs: number
    finalMessage: string | null
  }
  coverage: {
    totalSteps: number
    coveredSteps: number
    coverageRate: number
    uncoveredSteps: number[]
  }
  issues: string[]
}

export interface FlowSimulationStep {
  stepNo: number
  botMessage: string
  userInput: string
  matchedCondition: {
    type: string
    gotoStep: number
    keywords?: string[]
    pattern?: string
  } | null
  nextStep: number | null
  durationMs: number
}

export function listScriptFlows(params?: {
  is_enabled?: boolean
}): Promise<ScriptFlowListResponse> {
  return request({
    url: '/admin/script-flows',
    method: 'get',
    params
  })
}

export function getScriptFlow(flowId: string): Promise<ScriptFlowDetail> {
  return request({
    url: `/admin/script-flows/${flowId}`,
    method: 'get'
  })
}

export function createScriptFlow(data: ScriptFlowCreate): Promise<ScriptFlow> {
  return request({
    url: '/admin/script-flows',
    method: 'post',
    data
  })
}

export function updateScriptFlow(flowId: string, data: ScriptFlowUpdate): Promise<ScriptFlow> {
  return request({
    url: `/admin/script-flows/${flowId}`,
    method: 'put',
    data
  })
}

export function deleteScriptFlow(flowId: string): Promise<void> {
  return request({
    url: `/admin/script-flows/${flowId}`,
    method: 'delete'
  })
}

export function simulateScriptFlow(flowId: string, data: FlowSimulateRequest): Promise<FlowSimulateResponse> {
  return request({
    url: `/admin/script-flows/${flowId}/simulate`,
    method: 'post',
    data
  })
}

export type {
  ScriptFlow,
  ScriptFlowDetail,
  ScriptFlowCreate,
  ScriptFlowUpdate,
  ScriptFlowListResponse
}
