import { create } from 'zustand';
import { query } from '@/modules/query';
import { toast } from 'react-toastify';

// 审核，通过，驳回
export const appDomainStatus = ['audit', 'auditReject', 'auditPending', 'running', 'stop'] as const;

type AppDomainStatus = (typeof appDomainStatus)[number];
type Domain = {
  id: string;
  domain: string;
  appId?: string;
  status: AppDomainStatus;
  data?: any;
  uid?: string;
  createdAt: string;
  updatedAt: string;
};
interface Store {
  getDomainList: () => Promise<any>;
  updateDomain: (data: { domain: string; id: string; [key: string]: any }, opts?: { refresh?: boolean }) => Promise<any>;
  deleteDomain: (data: { id: string }) => Promise<any>;
  getDomainDetail: (data: { domain?: string; id?: string }) => Promise<any>;
  list: Domain[];
  setList: (list: Domain[]) => void;
  formData: any;
  setFormData: (formData: any) => void;
  showEditModal: boolean;
  setShowEditModal: (showEditModal: boolean) => void;
}

export const useDomainStore = create<Store>((set, get) => ({
  getDomainList: async () => {
    const res = await query.get({
      path: 'app.domain.manager',
      key: 'list',
    });
    if (res.code === 200) {
      set({ list: res.data?.list || [] });
    }
    return res;
  },
  updateDomain: async (data: any, opts?: { refresh?: boolean }) => {
    const res = await query.post({
      path: 'app.domain.manager',
      key: 'update',
      data,
    });
    if (res.code === 200) {
      const list = get().list;
      set({ list: list.map((item) => (item.id === data.id ? res.data : item)) });
      toast.success('更新成功');
      if (opts?.refresh ?? true) {
        get().getDomainList();
      }
    } else {
      toast.error(res.message || '更新失败');
    }
    return res;
  },
  deleteDomain: async (data: any) => {
    const res = await query.post({
      path: 'app.domain.manager',
      key: 'delete',
      data,
    });
    if (res.code === 200) {
      const list = get().list;
      set({ list: list.filter((item) => item.id !== data.id) });
      toast.success('删除成功');
    }
    return res;
  },
  getDomainDetail: async (data: any) => {
    const res = await query.post({
      path: 'app.domain.manager',
      key: 'get',
      data,
    });
    if (res.code === 200) {
      set({ formData: res.data });
    }
    return res;
  },
  list: [],
  setList: (list: any[]) => set({ list }),
  formData: {},
  setFormData: (formData: any) => set({ formData }),
  showEditModal: false,
  setShowEditModal: (showEditModal: boolean) => set({ showEditModal }),
}));
