import { invoke } from '@tauri-apps/api/core'

export interface Model {
  id: string
  model_number: string
  model_image: string
  created_at: string
  updated_at: string
  is_active: boolean
}

export interface CreateModelRequest {
  model_number: string
  model_image?: string
}

export interface UpdateModelRequest {
  model_number?: string
  model_image?: string
}

export interface ApiResponse<T> {
  status: boolean
  data?: T
  msg?: string
}

export class ModelService {
  /**
   * 尝试解析JSON响应
   */
  private static tryJsonParse(result: any): any {
    if (typeof result === 'string') {
      try {
        const parsed = JSON.parse(result)
        // 如果是JSON-RPC响应，提取result字段
        if (parsed.jsonrpc && 'result' in parsed) {
          return parsed.result
        }
        // 如果是普通JSON响应，直接返回
        return parsed
      } catch (error) {
        console.error('Failed to parse JSON:', error)
        return result
      }
    }
    return result
  }
  /**
   * 获取所有模特
   */
  static async getAllModels(): Promise<ApiResponse<Model[]>> {
    try {
      const result = await invoke('get_all_models')
      const parsed = this.tryJsonParse(result)

      // 检查后端返回的实际状态
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<Model[]>
      }

      // 如果没有状态信息，假设成功并包装数据
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<Model[]>
    } catch (error) {
      console.error('Failed to get all models:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 根据ID获取模特
   */
  static async getModelById(modelId: string): Promise<ApiResponse<Model>> {
    try {
      const result = await invoke('get_model_by_id', { modelId })
      return { status: true, msg: 'ok', data: this.tryJsonParse(result) } as ApiResponse<Model>
    } catch (error) {
      console.error('Failed to get model by id:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 创建新模特
   */
  static async createModel(request: CreateModelRequest): Promise<ApiResponse<Model>> {
    try {
      const result = await invoke('create_model', { request })
      const parsed = this.tryJsonParse(result)

      // 检查后端返回的实际状态
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<Model>
      }

      // 如果没有状态信息，假设成功
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<Model>
    } catch (error) {
      console.error('Failed to create model:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 更新模特
   */
  static async updateModel(
    modelId: string,
    request: UpdateModelRequest
  ): Promise<ApiResponse<Model>> {
    try {
      const result = await invoke('update_model', { modelId, request })
      return { status: true, msg: 'ok', data: this.tryJsonParse(result) } as ApiResponse<Model>
    } catch (error) {
      console.error('Failed to update model:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 删除模特
   */
  static async deleteModel(modelId: string): Promise<ApiResponse<boolean>> {
    try {
      const result = await invoke('delete_model', { modelId })
      const parsed = this.tryJsonParse(result)

      // 检查后端返回的实际状态
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<boolean>
      }

      // 如果没有状态信息，假设成功
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<boolean>
    } catch (error) {
      console.error('Failed to delete model:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 搜索模特
   */
  static async searchModels(keyword: string): Promise<ApiResponse<Model[]>> {
    try {
      const result = await invoke('search_models', { keyword })
      return { status: true, msg: 'ok', data: this.tryJsonParse(result) } as ApiResponse<Model[]>
    } catch (error) {
      console.error('Failed to search models:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }
}
