/**
 * 自定义表情服务
 * 管理用户自定义添加的表情包（云端存储）
 */

import { api } from './api';
import { uploadService } from './uploadService';

// 自定义表情类型
export interface CustomSticker {
  id: string;
  user_id: string;
  url: string;
  width: number;
  height: number;
  sort_order: number;
  created_at: string;
  updated_at: string;
}

// API 响应类型
interface GetStickersResponse {
  stickers: CustomSticker[];
}

interface AddStickerResponse {
  sticker: CustomSticker;
}

interface CheckStickerResponse {
  exists: boolean;
}

/**
 * 获取所有自定义表情
 */
export const getCustomStickers = async (): Promise<CustomSticker[]> => {
  try {
    const response = await api.get<GetStickersResponse>('/stickers');
    return response.data.stickers || [];
  } catch (error) {
    console.error('获取自定义表情失败:', error);
    return [];
  }
};

/**
 * 添加自定义表情（从URL）
 */
export const addStickerFromUrl = async (
  imageUrl: string,
  width?: number,
  height?: number
): Promise<CustomSticker | null> => {
  try {
    let finalUrl = imageUrl;
    const lowerUrl = imageUrl.toLowerCase();

    // 本地图片 URI 不能直接落库，先上传换成可访问的远程 URL
    if (lowerUrl.startsWith('file://') || lowerUrl.startsWith('content://')) {
      const uploadResult = await uploadService.uploadImage({ uri: imageUrl });
      if (!uploadResult?.url) {
        throw new Error('upload sticker image failed');
      }
      finalUrl = uploadResult.url;
    }

    const response = await api.post<AddStickerResponse>('/stickers', {
      url: finalUrl,
      width: width || 0,
      height: height || 0,
    });
    return response.data.sticker;
  } catch (error: any) {
    if (error.response?.status === 409) {
      return null;
    }
    console.error('添加自定义表情失败:', error);
    throw error;
  }
};

/**
 * 删除自定义表情
 */
export const deleteSticker = async (stickerId: string): Promise<boolean> => {
  try {
    await api.delete('/stickers', {
      data: { sticker_id: stickerId },
    });
    return true;
  } catch (error) {
    console.error('删除自定义表情失败:', error);
    return false;
  }
};

/**
 * 检查图片是否已经是自定义表情
 */
export const isStickerExists = async (imageUrl: string): Promise<boolean> => {
  try {
    const response = await api.get<CheckStickerResponse>('/stickers/check', { url: imageUrl });
    return response.data.exists;
  } catch (error) {
    console.error('检查表情是否存在失败:', error);
    return false;
  }
};

/**
 * 重新排序表情
 */
export const reorderStickers = async (orders: Record<string, number>): Promise<boolean> => {
  try {
    await api.post('/stickers/reorder', { orders });
    return true;
  } catch (error) {
    console.error('重新排序表情失败:', error);
    return false;
  }
};

/**
 * 批量删除表情
 */
export const batchDeleteStickers = async (stickerIds: string[]): Promise<{ success: number; failed: number }> => {
  let success = 0;
  let failed = 0;
  
  for (const stickerId of stickerIds) {
    try {
      await api.delete('/stickers', {
        data: { sticker_id: stickerId },
      });
      success++;
    } catch (error) {
      console.error(`删除表情 ${stickerId} 失败:`, error);
      failed++;
    }
  }
  
  return { success, failed };
};
