import { API_PREFIX } from '@/config'

export const login = (data) => {
  // 登录是公共接口，直接使用原生 fetch
  return fetch(`${API_PREFIX}/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'include',
    body: JSON.stringify(data),
  }).then(response => response.json())
}

export const logout = () => {
  return fetch(`${API_PREFIX}/logout`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'include',
  }).then(response => response.json())
}

/**
 * 用 refresh_token 刷新 access_token。
 * Dify 后端在响应里会通过 Set-Cookie 下发新的 access_token / refresh_token，
 * 浏览器自动覆盖同名 cookie，无需前端处理。
 * 成功返回 { result: 'success' }；失败抛错。
 */
export const refreshToken = () => {
  return fetch(`${API_PREFIX}/refresh-token`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'include',
  }).then(async response => {
    if (!response.ok) {
      const err = await response.json().catch(() => ({}))
      throw { code: err.code || response.status, message: err.message || '刷新 token 失败' }
    }
    const data = await response.json()
    // 后端在 body 里也返回了 access_token，存到 localStorage 覆盖旧的
    const newToken = data?.data?.access_token || data?.access_token || data?.token
    if (newToken) {
      try { localStorage.setItem('access_token', newToken) } catch (_) {}
    }
    return data
  })
}
