/**
 * Cover Avatar 封面形象 API 模块
 * ================================
 *
 * 提供图片上传、AI 抠图、本地封面形象库管理接口。
 */

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

// ====================== 类型 ======================

export interface CoverAvatar {
  id: string;
  name: string;
  imageUrl: string;
  localPath?: string;
  createdAt: string;
}

// ====================== HTTP API（后端直连） ======================

/**
 * 上传图片到七牛云
 */
export async function uploadImage(file: File): Promise<string> {
  const formData = new FormData();
  formData.append('file', file);
  const result = await client.postForm<{ url: string; key: string }>('/upload/image', formData);
  return result.url;
}

/**
 * AI 抠图（火山引擎 MediaKit）
 */
export async function removeBackground(imageUrl: string, scene = 'human'): Promise<string> {
  const result = await client.post<{ url: string }>('/image/remove-background', {
    imageUrl,
    scene,
  });
  return result.url;
}

// ====================== IPC 命令（本地存储） ======================

/**
 * 从本地加载封面形象库
 */
export async function loadCoverAvatars(): Promise<CoverAvatar[]> {
  const result = await invoke<{ code: number; data?: CoverAvatar[]; message: string }>('load_cover_avatars');
  if (result.code !== 200) {
    throw new Error(result.message || '加载封面形象库失败');
  }
  return result.data || [];
}

/**
 * 保存封面形象到本地
 */
export async function saveCoverAvatar(avatar: CoverAvatar): Promise<void> {
  const result = await invoke<{ code: number; message: string }>('save_cover_avatar', {
    args: {
      id: avatar.id,
      name: avatar.name,
      imageUrl: avatar.imageUrl,
      localPath: avatar.localPath,
      createdAt: avatar.createdAt,
    },
  });
  if (result.code !== 200) {
    throw new Error(result.message || '保存封面形象失败');
  }
}

/**
 * 删除本地封面形象
 */
export async function deleteCoverAvatar(id: string): Promise<void> {
  const result = await invoke<{ code: number; message: string }>('delete_cover_avatar_cmd', { id });
  if (result.code !== 200) {
    throw new Error(result.message || '删除封面形象失败');
  }
}

/**
 * 保存封面形象图片文件到本地（base64 编码）
 */
export async function saveCoverAvatarImage(args: {
  avatarId: string;
  imageData: string;
  ext: string;
}): Promise<string> {
  const result = await invoke<{ code: number; data?: string; message: string }>('save_cover_avatar_image', {
    args: {
      avatarId: args.avatarId,
      imageData: args.imageData,
      ext: args.ext,
    },
  });
  if (result.code !== 200 || !result.data) {
    throw new Error(result.message || '保存封面形象图片失败');
  }
  return result.data;
}
