import { request } from '@/api/request'

export interface AutomationScript {
  id: number
  name: string
  resource_category: string
  command_template: string
  approval_level: string
  rollback_command?: string
  rollback_required: boolean
  description?: string
  status: string
  created_at?: string
  updated_at?: string
}

export interface AutomationExecution {
  id: number
  script_id: number
  mode: string
  status: string
  resource_uid: string
  rendered_command: string
  incident_id?: number
  ticket_id?: number
  approval_level: string
  approved_by?: string
  approved_at?: string
  operator?: string
  started_at?: string
  finished_at?: string
  timeout_sec?: number
  stdout?: string
  stderr?: string
  exit_code?: number
  error?: string
  audit_trail?: string
  created_at?: string
  updated_at?: string
}

export interface AutomationRunRequest {
  resource_uid: string
  incident_id?: number
  ticket_id?: number
  operator?: string
  approver?: string
  approved?: boolean
  mode?: 'execute' | 'rollback'
  variables?: Record<string, string>
}

export interface PageResponse<T> {
  total: number
  page: number
  page_size: number
  data: T[]
}

export const fetchAutomationScripts = (params?: Record<string, any>) =>
  request.get<{ details: PageResponse<AutomationScript> }>('/DC-Control/v1/automation/scripts', { params })

export const createAutomationScript = (data: Partial<AutomationScript>) =>
  request.post<{ details: AutomationScript }>('/DC-Control/v1/automation/scripts', data)

export const updateAutomationScript = (id: number, data: Partial<AutomationScript>) =>
  request.put(`/DC-Control/v1/automation/scripts/${id}`, data)

export const deleteAutomationScript = (id: number) => request.delete(`/DC-Control/v1/automation/scripts/${id}`)

export const dryRunAutomationScript = (id: number, data: AutomationRunRequest) =>
  request.post<{ details: AutomationExecution }>(`/DC-Control/v1/automation/scripts/${id}/dry-run`, data)

export const requestAutomationExecution = (id: number, data: AutomationRunRequest) =>
  request.post<{ details: AutomationExecution }>(`/DC-Control/v1/automation/scripts/${id}/executions`, data)

export const executeAutomationScript = (id: number, data: AutomationRunRequest) =>
  request.post<{ details: AutomationExecution }>(`/DC-Control/v1/automation/scripts/${id}/execute`, data)

export const rollbackAutomationScript = (id: number, data: AutomationRunRequest) =>
  request.post<{ details: AutomationExecution }>(`/DC-Control/v1/automation/scripts/${id}/rollback`, data)

export const fetchAutomationExecutions = (params?: Record<string, any>) =>
  request.get<{ details: PageResponse<AutomationExecution> }>('/DC-Control/v1/automation/executions', { params })

export const approveAutomationExecution = (id: number, data: { approver: string; operator?: string }) =>
  request.post<{ details: AutomationExecution }>(`/DC-Control/v1/automation/executions/${id}/approve`, data)
