import axios from 'axios'
import type { ApiResponse } from '@/types/api'
import { useAuthStore } from '@/stores/auth'

export const http = axios.create({
  baseURL: '',
  timeout: 20000,
})

http.interceptors.request.use((config) => {
  const auth = useAuthStore()
  if (auth.token) {
    config.headers.Authorization = `Bearer ${auth.token}`
  }
  return config
})

http.interceptors.response.use(
  (response) => response.data,
  async (error) => {
    const auth = useAuthStore()
    if (error.response?.status === 401) {
      auth.clearSession()
      if (!window.location.hash.startsWith('#/login')) {
        const redirect = window.location.hash.slice(1) || '/'
        window.location.href = `/#/login?redirect=${encodeURIComponent(redirect)}`
      }
    }
    return Promise.reject(error)
  },
)

export async function apiGet<T>(url: string, params?: Record<string, unknown>): Promise<ApiResponse<T>> {
  return http.get(url, { params }) as unknown as ApiResponse<T>
}

export async function apiPost<T>(url: string, data?: unknown): Promise<ApiResponse<T>> {
  return http.post(url, data) as unknown as ApiResponse<T>
}

export async function apiPut<T>(url: string, data?: unknown): Promise<ApiResponse<T>> {
  return http.put(url, data) as unknown as ApiResponse<T>
}

export function apiPutKeepalive(url: string, data?: unknown) {
  const auth = useAuthStore()
  return fetch(url, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      ...(auth.token ? { Authorization: `Bearer ${auth.token}` } : {}),
    },
    body: JSON.stringify(data ?? {}),
    keepalive: true,
  })
}

export async function apiDelete<T>(url: string): Promise<ApiResponse<T>> {
  return http.delete(url) as unknown as ApiResponse<T>
}
