import axios from 'axios';
import { getApiBaseUrl } from '../config/apiBase';

const API_BASE_URL = getApiBaseUrl();

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
});

api.interceptors.response.use(
  (response) => {
    const contentType = response?.headers?.['content-type'] || '';
    if (typeof response.data === 'string') {
      const trimmed = response.data.trim().toLowerCase();
      const looksLikeHtml =
        contentType.includes('text/html') ||
        trimmed.startsWith('<!doctype') ||
        trimmed.startsWith('<html');

      if (looksLikeHtml) {
        throw new Error(
          `API 返回了 HTML（疑似请求打到了前端自身域名/SPA重写），请检查 Cloudflare Pages 环境变量 REACT_APP_API_URL。当前 baseURL: ${API_BASE_URL}`
        );
      }
    }

    return response;
  },
  (error) => Promise.reject(error)
);

// 获取网站设置
export const getSettings = async () => {
  const response = await api.get('/settings');
  return response.data;
};

const buildPagingParams = (page, pageSize) => {
  const params = {};
  if (page) params.page = page;
  if (pageSize) params.page_size = pageSize;
  return params;
};

// 获取所有作品（支持分页）
export const getWorks = async (page = null, pageSize = null) => {
  const response = await api.get('/works', {
    params: buildPagingParams(page, pageSize),
  });
  return response.data;
};

// 获取单个作品详情
export const getWorkDetail = async (workId) => {
  const response = await api.get(`/works/${workId}`);
  return response.data;
};

// 搜索作品
export const searchWorks = async (query = '', category = '', page = null, pageSize = null) => {
  const params = new URLSearchParams();
  if (query) params.append('q', query);
  if (category) params.append('category', category);
  if (page) params.append('page', page);
  if (pageSize) params.append('page_size', pageSize);
  
  const response = await api.get(`/search?${params.toString()}`);
  return response.data;
};

// 获取所有分类
export const getCategories = async () => {
  const response = await api.get('/categories');
  return response.data;
};

// 点赞作品
export const likeWork = async (workId) => {
  const response = await api.post(`/like/${workId}`);
  return response.data;
};

export default api;
