import { useUserStore } from '@/store/user'
import { fetch } from '@tauri-apps/plugin-http'

type CommonOption = {
  url: string
  query?: Record<string, string>
  noAuth?: boolean
  headers?: Record<string, string>
}

type GetOption = {
  method: 'GET' | 'DELETE'
}

type PostOption = {
  method: 'POST' | 'PUT'
  data?: unknown
}

type RequestOptions = CommonOption & (GetOption | PostOption)

type Response<T> = {
  code: number
  data: T
  msg: string
}

export const request = async <T = void>(config: RequestOptions) => {
  const { noAuth, url, headers, method, query } = config
  if (!noAuth) {
    const { getToken } = useUserStore()
    headers['Access-Token'] = getToken
  }
  const reqPath = new URL(url, import.meta.env.VITE_BASE_URL || '')
  if (query) Object.keys(query).forEach((key) => reqPath.searchParams.append(key, query[key]))

  try {
    console.log('reqPath.href: ', reqPath.href)
    let body = null
    if (config.method === 'POST' || (config.method === 'PUT' && config.data)) {
      body = JSON.stringify(config.data)
    }

    const response = await fetch(reqPath.href, {
      method,
      headers: {
        'Content-Type': 'application/json',
        ...headers,
      },
      body,
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const { code, data, msg } = (await response.json()) as Response<T>
    if (code !== 200) {
      throw new Error(msg)
    }
    return data
  } catch (error) {
    console.error('Request failed', error)
    throw error
  }
}
