import axios from 'axios';
import {
  GadminCrud as gadminDataProvider,
  applyErrorInterceptor,
  customRequest as baseCustomRequest,
} from '@gadmin2n/react-common';
import { login, requestHeaders } from './login';
import { getApiUrl } from 'config/http';
// Re-export Prisma helpers from react-common for backward compatibility
export { convertPrismaDecimal, isPrismaDecimal } from '@gadmin2n/react-common';

const apiUrl = getApiUrl();

const axiosInstance = axios.create();

// 注入 auth header
axiosInstance.interceptors.request.use(
  (config) => {
    if (config.headers) {
      Object.assign(config.headers, requestHeaders());
    }
    return config;
  },
  (error) => Promise.reject(error),
);

// 处理 401 跳转登录、403 跳权限页（app 层特有逻辑，须在 applyErrorInterceptor 之前注册）
axiosInstance.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error?.response?.status === 401) {
      console.log('login expired');
      login();
      // 返回pending状态的promise，以免后续代码出错
      return new Promise(() => {});
    }
    if (error?.response?.status === 403) {
      // 已经在 /403 页面则不再跳转，防止死循环
      if (!window.location.pathname.endsWith('/403')) {
        window.location.href = '/403';
      }
      return new Promise(() => {});
    }
    return Promise.reject(error);
  },
);

// 统一错误格式化（复用公共库逻辑，消除重复代码）
applyErrorInterceptor(axiosInstance);

export const gadminCrudProvider = gadminDataProvider(apiUrl, axiosInstance);

/**
 * 直接用 fetch 发 findMany 请求（绕开 refine DataProvider，适合非 React 上下文）
 */
export async function findMany<T>(
  resource: string,
  params: Record<string, any>,
): Promise<T[]> {
  const url = `${apiUrl}/${resource}/findMany`;
  const res = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      ...requestHeaders(),
    },
    body: JSON.stringify(params),
  });
  if (!res.ok) throw new Error(`findMany ${resource} failed: ${res.status}`);
  const data = await res.json();
  return (data.data ?? []) as T[];
}

/**
 * 向后端发送原始 HTTP 请求（绕开 refine DataProvider）。
 * 底层复用公共库的 customRequest，自动携带当前 app 的 auth header 及错误拦截。
 */
export async function customRequest<T>(
  urlPath: string,
  method: string,
  params?: Record<string, any>,
) {
  return baseCustomRequest<T>(axiosInstance, apiUrl, urlPath, method, params);
}
