import axios, { AxiosError } from 'axios';
import { message } from 'antd';

export interface ApiResponse<T> {
  success: boolean;
  code: string;
  message: string;
  data: T;
  timestamp: string;
}

export interface PageResponse<T> {
  list: T[];
  pageNum: number;
  pageSize: number;
  total: number;
  pages: number;
}

const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL ?? '',
  timeout: 60_000,
});

api.interceptors.request.use((config) => {
  const token = localStorage.getItem('accessToken');
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

api.interceptors.response.use(
  (res) => {
    const body = res.data;
    if (body && typeof body === 'object' && 'success' in body && body.success === false) {
      message.error(body.message ?? '오류가 발생했습니다');
      return Promise.reject(body);
    }
    return res;
  },
  (err: AxiosError<ApiResponse<unknown>>) => {
    const status = err.response?.status;
    const body = err.response?.data;
    if (status === 401) {
      localStorage.removeItem('accessToken');
      window.location.href = '/login';
    } else if (status === 403) {
      message.error(body?.message ?? '권한이 없습니다');
    } else {
      message.error(body?.message ?? err.message ?? '서버 오류');
    }
    return Promise.reject(err);
  },
);

export default api;

/** ApiResponse<T> 의 data 만 풀어서 반환 */
export async function unwrap<T>(p: Promise<{ data: ApiResponse<T> }>): Promise<T> {
  const res = await p;
  return res.data.data;
}
