import type { Dispatch, SetStateAction } from 'react';
import type { GatewayRunnerPolicy, GatewayRunnerPolicyUpsertRequest, RuntimePolicySet, RuntimePolicySetUpsertRequest } from '@easyai-ai-gateway/contracts';
import { createRuntimePolicySet, deleteRuntimePolicySet, updateRunnerPolicy, updateRuntimePolicySet } from '../api';
import type { LoadState } from '../types';

export function useRuntimePolicySetOperations(input: {
  setCoreMessage: Dispatch<SetStateAction<string>>;
  setCoreState: Dispatch<SetStateAction<LoadState>>;
  setRunnerPolicy: Dispatch<SetStateAction<GatewayRunnerPolicy | null>>;
  setRuntimePolicySets: Dispatch<SetStateAction<RuntimePolicySet[]>>;
  token: string;
}) {
  async function saveRunnerPolicy(payload: GatewayRunnerPolicyUpsertRequest) {
    if (!input.token) throw new Error('请先登录后再维护调度策略');
    input.setCoreState('loading');
    input.setCoreMessage('');
    try {
      const policy = await updateRunnerPolicy(input.token, payload);
      input.setRunnerPolicy(policy);
      input.setCoreState('ready');
      input.setCoreMessage('全局调度策略已更新。');
    } catch (err) {
      input.setCoreState('error');
      input.setCoreMessage(err instanceof Error ? err.message : '全局调度策略保存失败');
      throw err;
    }
  }

  async function saveRuntimePolicySet(payload: RuntimePolicySetUpsertRequest, policySetId?: string) {
    if (!input.token) throw new Error('请先登录后再维护运行策略');
    input.setCoreState('loading');
    input.setCoreMessage('');
    try {
      const policySet = policySetId
        ? await updateRuntimePolicySet(input.token, policySetId, payload)
        : await createRuntimePolicySet(input.token, payload);
      input.setRuntimePolicySets((current) => [policySet, ...current.filter((item) => item.id !== policySet.id)]);
      input.setCoreState('ready');
      input.setCoreMessage(policySetId ? '运行策略已更新。' : '运行策略已新增。');
    } catch (err) {
      input.setCoreState('error');
      input.setCoreMessage(err instanceof Error ? err.message : '运行策略保存失败');
      throw err;
    }
  }

  async function removeRuntimePolicySet(policySetId: string) {
    if (!input.token) throw new Error('请先登录后再维护运行策略');
    input.setCoreState('loading');
    input.setCoreMessage('');
    try {
      await deleteRuntimePolicySet(input.token, policySetId);
      input.setRuntimePolicySets((current) => current.filter((item) => item.id !== policySetId));
      input.setCoreState('ready');
      input.setCoreMessage('运行策略已删除。');
    } catch (err) {
      input.setCoreState('error');
      input.setCoreMessage(err instanceof Error ? err.message : '运行策略删除失败');
      throw err;
    }
  }

  return { removeRuntimePolicySet, saveRunnerPolicy, saveRuntimePolicySet };
}
