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;
  getStatFile: () => Promise<any>;
  updateMeta: (metadata: any) => Promise<any>;
}

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) {
      // set({ resource: { ...res.data, name: resource?.name } });
      getStatFile();
    } else {
      toast.error(res.message || '更新元数据失败');
    }
  },
}));
