import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { CmsAppConfig, CmsAppConfigParam, BatchSaveRequest } from './model';
import {MODULES_API_URL} from '@/config/setting';

/**
 * 分页查询应用配置
 */
export async function pageCmsAppConfig(params: CmsAppConfigParam) {
  const res = await request.get<ApiResult<PageResult<CmsAppConfig>>>(
    MODULES_API_URL + '/cms/cms-app-config/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 获取应用配置列表
 */
export async function listCmsAppConfig(params?: CmsAppConfigParam) {
  const res = await request.get<ApiResult<CmsAppConfig[]>>(
    MODULES_API_URL + '/cms/cms-app-config/list',
    {
      params
    }
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 根据应用ID获取配置映射
 */
export async function getConfigsMap(productId: number) {
  const res = await request.get<ApiResult<Record<string, any>>>(
    MODULES_API_URL + `/cms/cms-app-config/map/${productId}`
  );
  if (res.data.code === 0) {
    return res.data.data || {};
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 获取单个配置值
 */
export async function getConfigValue(productId: number, configKey: string) {
  const res = await request.get<ApiResult<string>>(
    MODULES_API_URL + '/cms/cms-app-config/value',
    {
      params: { productId, configKey }
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 保存配置
 */
export async function saveCmsAppConfig(data: CmsAppConfig) {
  const res = await request.post<ApiResult<void>>(
    MODULES_API_URL + '/cms/cms-app-config',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量保存配置
 */
export async function batchSaveCmsAppConfig(data: BatchSaveRequest) {
  const res = await request.post<ApiResult<void>>(
    MODULES_API_URL + '/cms/cms-app-config/batch',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 更新配置
 */
export async function updateCmsAppConfig(data: CmsAppConfig) {
  const res = await request.put<ApiResult<void>>(
    MODULES_API_URL + '/cms/cms-app-config',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除配置
 */
export async function deleteCmsAppConfig(configId: number) {
  const res = await request.delete<ApiResult<void>>(
    MODULES_API_URL + `/cms/cms-app-config/${configId}`
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
