import apiClient from './client'

// 类型定义
export interface RegexScript {
  id: number
  userId: number
  name: string
  findRegex: string
  replaceWith: string
  trimStrings: string[]
  placement: number
  disabled: boolean
  markdownOnly: boolean
  runOnEdit: boolean
  promptOnly: boolean
  substituteRegex: boolean
  minDepth?: number
  maxDepth?: number
  scope: number
  ownerCharId?: number
  ownerPresetId?: number
  order: number
  extensions: Record<string, any>
  createdAt: string
  updatedAt: string
}

export interface CreateRegexScriptRequest {
  name: string
  findRegex: string
  replaceWith?: string
  trimStrings?: string[]
  placement?: number
  disabled?: boolean
  markdownOnly?: boolean
  runOnEdit?: boolean
  promptOnly?: boolean
  substituteRegex?: boolean
  minDepth?: number
  maxDepth?: number
  scope?: number
  ownerCharId?: number
  ownerPresetId?: number
  order?: number
  extensions?: Record<string, any>
}

export interface UpdateRegexScriptRequest {
  name?: string
  findRegex?: string
  replaceWith?: string
  trimStrings?: string[]
  placement?: number
  disabled?: boolean
  markdownOnly?: boolean
  runOnEdit?: boolean
  promptOnly?: boolean
  substituteRegex?: boolean
  minDepth?: number
  maxDepth?: number
  scope?: number
  ownerCharId?: number
  ownerPresetId?: number
  order?: number
  extensions?: Record<string, any>
}

export interface GetRegexScriptListRequest {
  page?: number
  pageSize?: number
  keyword?: string
  scope?: number
  ownerCharId?: number
}

export interface RegexScriptListResponse {
  list: RegexScript[]
  total: number
  page: number
  pageSize: number
}

// API 方法
export const regexAPI = {
  // 创建正则脚本
  create: (data: CreateRegexScriptRequest): Promise<{ data: RegexScript }> => {
    return apiClient.post('/app/regex', data)
  },

  // 获取正则脚本列表
  getList: (params?: GetRegexScriptListRequest): Promise<{ data: RegexScriptListResponse }> => {
    return apiClient.get('/app/regex', { params })
  },

  // 获取正则脚本详情
  getById: (id: number): Promise<{ data: RegexScript }> => {
    return apiClient.get(`/app/regex/${id}`)
  },

  // 更新正则脚本
  update: (id: number, data: UpdateRegexScriptRequest) => {
    return apiClient.put(`/app/regex/${id}`, data)
  },

  // 删除正则脚本
  delete: (id: number) => {
    return apiClient.delete(`/app/regex/${id}`)
  },

  // 测试正则脚本
  test: (id: number, testString: string): Promise<{ data: { original: string; result: string; success: boolean; error?: string } }> => {
    return apiClient.post(`/app/regex/${id}/test`, { testString })
  },
}

// 保持向后兼容
export const regexScriptApi = regexAPI
