import request from '@/utils/request';
import { withCreditUserScope } from '@/api/credit/utils/data-scope';

import type { ApiResult } from '@/api';

/**
 * 修正某个信用模块数据的主体企业归属（按名称匹配回填 companyId）
 *
 * 后端约定: POST /api/credit/{module}/company-id/refresh
 * 例如: module = "credit-judgment-debtor"
 */
export async function refreshCreditCompanyId(
  module: string,
  params?: {
    onlyNull?: boolean;
    limit?: number;
  }
) {
  const scopedParams = withCreditUserScope(params) as
    | Record<string, unknown>
    | undefined;
  const query = scopedParams
    ? '?' +
      Object.keys(scopedParams)
        .filter(
          (key) =>
            scopedParams[key] !== undefined && scopedParams[key] !== null
        )
        .map(
          (key) =>
            `${encodeURIComponent(key)}=${encodeURIComponent(
              String(scopedParams[key])
            )}`
        )
        .join('&')
    : '';

  const res = await request.post<ApiResult<unknown>>(
    `/credit/${module}/company-id/refresh${query}`
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}
