import type { Dispatch, SetStateAction } from 'react';
import type {
  BaseModelCatalogItem,
  BaseModelUpsertRequest,
  CatalogProvider,
  CatalogProviderUpsertRequest,
} from '@easyai-ai-gateway/contracts';
import {
  createBaseModel,
  createCatalogProvider,
  deleteBaseModel,
  deleteCatalogProvider,
  resetAllBaseModels,
  resetBaseModel,
  updateBaseModel,
  updateCatalogProvider,
} from '../api';
import type { LoadState } from '../types';

export function useCatalogOperations(input: {
  setBaseModels: Dispatch<SetStateAction<BaseModelCatalogItem[]>>;
  setCoreMessage: Dispatch<SetStateAction<string>>;
  setCoreState: Dispatch<SetStateAction<LoadState>>;
  setProviders: Dispatch<SetStateAction<CatalogProvider[]>>;
  token: string;
}) {
  async function saveProvider(payload: CatalogProviderUpsertRequest, providerId?: string) {
    if (!input.token) throw new Error('请先登录后再维护模型厂商');
    input.setCoreState('loading');
    input.setCoreMessage('');
    try {
      const provider = providerId
        ? await updateCatalogProvider(input.token, providerId, payload)
        : await createCatalogProvider(input.token, payload);
      input.setProviders((current) => [provider, ...current.filter((item) => item.id !== provider.id)]);
      input.setCoreState('ready');
      input.setCoreMessage(providerId ? '模型厂商已更新。' : '模型厂商已新增。');
    } catch (err) {
      input.setCoreState('error');
      input.setCoreMessage(err instanceof Error ? err.message : '模型厂商保存失败');
      throw err;
    }
  }

  async function removeProvider(providerId: string) {
    if (!input.token) throw new Error('请先登录后再维护模型厂商');
    input.setCoreState('loading');
    input.setCoreMessage('');
    try {
      await deleteCatalogProvider(input.token, providerId);
      input.setProviders((current) => current.filter((item) => item.id !== providerId));
      input.setCoreState('ready');
      input.setCoreMessage('模型厂商已删除。');
    } catch (err) {
      input.setCoreState('error');
      input.setCoreMessage(err instanceof Error ? err.message : '模型厂商删除失败');
      throw err;
    }
  }

  async function saveBaseModel(payload: BaseModelUpsertRequest, baseModelId?: string) {
    if (!input.token) throw new Error('请先登录后再维护基准模型');
    input.setCoreState('loading');
    input.setCoreMessage('');
    try {
      const model = baseModelId
        ? await updateBaseModel(input.token, baseModelId, payload)
        : await createBaseModel(input.token, payload);
      input.setBaseModels((current) => [model, ...current.filter((item) => item.id !== model.id)]);
      input.setCoreState('ready');
      input.setCoreMessage(baseModelId ? '基准模型已更新。' : '基准模型已新增。');
    } catch (err) {
      input.setCoreState('error');
      input.setCoreMessage(err instanceof Error ? err.message : '基准模型保存失败');
      throw err;
    }
  }

  async function removeBaseModel(baseModelId: string) {
    if (!input.token) throw new Error('请先登录后再维护基准模型');
    input.setCoreState('loading');
    input.setCoreMessage('');
    try {
      await deleteBaseModel(input.token, baseModelId);
      input.setBaseModels((current) => current.filter((item) => item.id !== baseModelId));
      input.setCoreState('ready');
      input.setCoreMessage('基准模型已删除。');
    } catch (err) {
      input.setCoreState('error');
      input.setCoreMessage(err instanceof Error ? err.message : '基准模型删除失败');
      throw err;
    }
  }

  async function resetBaseModelToDefault(baseModelId: string) {
    if (!input.token) throw new Error('请先登录后再维护基准模型');
    input.setCoreState('loading');
    input.setCoreMessage('');
    try {
      const model = await resetBaseModel(input.token, baseModelId);
      input.setBaseModels((current) => current.map((item) => (item.id === model.id ? model : item)));
      input.setCoreState('ready');
      input.setCoreMessage('基准模型已重置为系统默认。');
    } catch (err) {
      input.setCoreState('error');
      input.setCoreMessage(err instanceof Error ? err.message : '基准模型重置失败');
      throw err;
    }
  }

  async function resetAllBaseModelsToDefault() {
    if (!input.token) throw new Error('请先登录后再维护基准模型');
    input.setCoreState('loading');
    input.setCoreMessage('');
    try {
      const response = await resetAllBaseModels(input.token);
      const resetModels = new Map(response.items.map((item) => [item.id, item]));
      input.setBaseModels((current) => current.map((item) => resetModels.get(item.id) ?? item));
      input.setCoreState('ready');
      input.setCoreMessage(`已重置 ${response.items.length} 个系统内置基准模型。`);
    } catch (err) {
      input.setCoreState('error');
      input.setCoreMessage(err instanceof Error ? err.message : '基准模型批量重置失败');
      throw err;
    }
  }

  return {
    removeBaseModel,
    removeProvider,
    resetAllBaseModelsToDefault,
    resetBaseModelToDefault,
    saveBaseModel,
    saveProvider,
  };
}
