/**
 * Cover Avatar Store - Zustand
 * ==============================
 *
 * 管理封面形象（用户上传人物照片 → AI 抠图）的全局状态。
 */

import { create } from 'zustand';
import type { CoverAvatar } from '../api/modules/coverAvatar';
import * as coverAvatarApi from '../api/modules/coverAvatar';

interface CoverAvatarState {
  // 封面形象列表
  coverAvatars: CoverAvatar[];
  // 加载状态
  isLoading: boolean;
}

interface CoverAvatarActions {
  // 加载封面形象库
  loadCoverAvatars: () => Promise<void>;
  // 添加封面形象（上传 → 抠图 → 保存）
  addCoverAvatar: (file: File, name: string) => Promise<CoverAvatar>;
  // 重命名封面形象
  renameCoverAvatar: (id: string, name: string) => Promise<void>;
  // 删除封面形象
  deleteCoverAvatar: (id: string) => Promise<void>;
  // 重置
  reset: () => void;
}

const initialState: CoverAvatarState = {
  coverAvatars: [],
  isLoading: false,
};

export const useCoverAvatarStore = create<CoverAvatarState & CoverAvatarActions>()(
  (set) => ({
    ...initialState,

    // ====================== 加载 ======================

    loadCoverAvatars: async () => {
      set({ isLoading: true });
      try {
        const avatars = await coverAvatarApi.loadCoverAvatars();
        set({ coverAvatars: avatars });
      } catch (err) {
        console.error('[CoverAvatarStore] 加载封面形象库失败:', err);
      } finally {
        set({ isLoading: false });
      }
    },

    // ====================== 添加 ======================

    addCoverAvatar: async (file: File, name: string) => {
      // 1. 上传原始图片到七牛云
      const originalUrl = await coverAvatarApi.uploadImage(file);

      // 2. AI 抠图
      const removedBgUrl = await coverAvatarApi.removeBackground(originalUrl);

      // 3. 下载抠图结果并转 base64
      const response = await fetch(removedBgUrl);
      if (!response.ok) {
        throw new Error(`下载抠图结果失败: ${response.status}`);
      }
      const blob = await response.blob();
      const arrayBuffer = await blob.arrayBuffer();
      const base64Data = btoa(
        new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), '')
      );

      // 4. 保存图片到本地
      const avatarId = crypto.randomUUID();
      const ext = 'png';
      const localPath = await coverAvatarApi.saveCoverAvatarImage({
        avatarId,
        imageData: base64Data,
        ext,
      });

      // 5. 保存元数据到本地 JSON
      const avatar: CoverAvatar = {
        id: avatarId,
        name,
        imageUrl: removedBgUrl,
        localPath,
        createdAt: new Date().toISOString(),
      };
      await coverAvatarApi.saveCoverAvatar(avatar);

      set(state => ({ coverAvatars: [avatar, ...state.coverAvatars] }));
      return avatar;
    },

    // ====================== 重命名 ======================

    renameCoverAvatar: async (id: string, name: string) => {
      set(state => {
        const updated = state.coverAvatars.map(a =>
          a.id === id ? { ...a, name } : a
        );
        const target = updated.find(a => a.id === id);
        if (target) {
          coverAvatarApi.saveCoverAvatar(target).catch(err => {
            console.error('[CoverAvatarStore] 重命名保存失败:', err);
          });
        }
        return { coverAvatars: updated };
      });
    },

    // ====================== 删除 ======================

    deleteCoverAvatar: async (id: string) => {
      await coverAvatarApi.deleteCoverAvatar(id);
      set(state => ({
        coverAvatars: state.coverAvatars.filter(a => a.id !== id),
      }));
    },

    // ====================== 重置 ======================

    reset: () => set(initialState),
  })
);
