import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { AppConfig, AppConfigParam, BatchSaveRequest } from './model';
import {APP_API_URL} from '@/config/setting';

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

/**
 * 获取应用配置列表
 */
export async function listAppConfig(params?: AppConfigParam) {
  const res = await request.get<ApiResult<AppConfig[]>>(
    APP_API_URL + '/app-config',
    {
      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>>>(
    APP_API_URL + `/app/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>>(
    APP_API_URL + '/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 saveAppConfig(data: AppConfig) {
  const res = await request.post<ApiResult<void>>(
    APP_API_URL + '/app-config',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

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

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

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