import type { Dispatch, SetStateAction } from 'react';
import type { PricingRuleSet, PricingRuleSetUpsertRequest } from '@easyai-ai-gateway/contracts';
import { createPricingRuleSet, deletePricingRuleSet, updatePricingRuleSet } from '../api';
import type { LoadState } from '../types';

export function usePricingRuleSetOperations(input: {
  setCoreMessage: Dispatch<SetStateAction<string>>;
  setCoreState: Dispatch<SetStateAction<LoadState>>;
  setPricingRuleSets: Dispatch<SetStateAction<PricingRuleSet[]>>;
  token: string;
}) {
  async function savePricingRuleSet(payload: PricingRuleSetUpsertRequest, ruleSetId?: string) {
    if (!input.token) throw new Error('请先登录后再维护定价规则');
    input.setCoreState('loading');
    input.setCoreMessage('');
    try {
      const item = ruleSetId
        ? await updatePricingRuleSet(input.token, ruleSetId, payload)
        : await createPricingRuleSet(input.token, payload);
      input.setPricingRuleSets((current) => [item, ...current.filter((ruleSet) => ruleSet.id !== item.id)]);
      input.setCoreState('ready');
      input.setCoreMessage(ruleSetId ? '定价规则已更新。' : '定价规则已新增。');
    } catch (err) {
      input.setCoreState('error');
      input.setCoreMessage(err instanceof Error ? err.message : '定价规则保存失败');
      throw err;
    }
  }

  async function removePricingRuleSet(ruleSetId: string) {
    if (!input.token) throw new Error('请先登录后再维护定价规则');
    input.setCoreState('loading');
    input.setCoreMessage('');
    try {
      await deletePricingRuleSet(input.token, ruleSetId);
      input.setPricingRuleSets((current) => current.filter((item) => item.id !== ruleSetId));
      input.setCoreState('ready');
      input.setCoreMessage('定价规则已删除。');
    } catch (err) {
      input.setCoreState('error');
      input.setCoreMessage(err instanceof Error ? err.message : '定价规则删除失败');
      throw err;
    }
  }

  return { removePricingRuleSet, savePricingRuleSet };
}
