import { create } from 'zustand';
import { Resource } from './resource';
import { query } from '@kevisual/resources/modules/query';
import { toast } from 'react-toastify';

interface ResourceFileStore {
  resource: Resource | null;
  setResource: (resource: Resource) => void;
  openDrawer: boolean;
  setOpenDrawer: (openDrawer: boolean) => void;
  prefix: string;
  setPrefix: (prefix: string, replace?: string) => void;
  /**
   * 需要先设置prefix
   * @returns
   */
  getStatFile: () => Promise<any>;
  updateMeta: (metadata: any) => Promise<any>;
  /**
   * 删除文件
   * @param resource 文件
   * @param opts 选项
   * @returns
   */
  deleteFile: (resource: Resource, opts?: { onSuccess?: (res: any) => void }) => Promise<void>;
  /**
   * 删除目录
   * @param prefix 目录
   * @param opts 选项
   * @returns
   */
  deleteDirectory: (prefix: string, opts?: { onSuccess?: (res: any) => void }) => Promise<void>;
  once: ((data: any) => any) | null;
  setOnce: (data: any) => void;
}

export const useResourceFileStore = create<ResourceFileStore>((set, get) => ({
  resource: null,
  setResource: (resource) => set({ resource }),
  openDrawer: false,
  setOpenDrawer: (openDrawer) => set({ openDrawer }),
  prefix: '',
  setPrefix: (prefix, replace) => set({ prefix: replace ? prefix.replace(replace, '') : prefix }),
  getStatFile: async () => {
    const { prefix } = get();
    const res = await query.post({
      path: 'file',
      key: 'stat',
      data: {
        prefix,
      },
    });
    if (res.code === 200) {
      set({ resource: { ...res.data, name: prefix } });
    }
  },
  updateMeta: async (metadata: any) => {
    const { resource, getStatFile } = get();
    const res = await query.post({
      path: 'file',
      key: 'update-metadata',
      data: {
        prefix: resource?.name,
        metadata: metadata,
      },
    });
    if (res.code === 200) {
      toast.success('Update metadata success');
      getStatFile();
    } else {
      toast.error(res.message || '更新元数据失败');
    }
  },
  deleteFile: async (resource: Resource, opts?: { onSuccess?: (res: any) => void }) => {
    const { once, setOnce } = get();
    const name = resource.name;
    if (!name) {
      toast.error('Resource is not a file');
      return;
    }
    const res = await query.post({
      path: 'file',
      key: 'delete',
      data: {
        prefix: name,
      },
    });
    if (res.code === 200) {
      toast.success('Delete file success');
      opts?.onSuccess?.(res);
      once?.(res);
      setOnce(null);
    } else {
      toast.error(res.message || 'Request failed');
    }
  },
  deleteDirectory: async (prefix: string, opts?: { onSuccess?: (res: any) => void }) => {
    if (!prefix) {
      toast.error('Directory name is required');
      return;
    }
    if (prefix.endsWith('/')) {
      toast.error('Directory name cannot end with a slash');
      return;
    }

    const res = await query.post({
      path: 'file',
      key: 'delete-all',
      data: {
        directory: prefix,
      },
    });
    if (res.code === 200) {
      toast.success('Delete directory success');
      opts?.onSuccess?.(res);
    } else {
      toast.error(res.message || 'Request failed');
    }
  },
  once: null,
  setOnce: (data: any) => set({ once: data }),
}));
