import { getAccessToken, getTenantId, getVisitTenantId } from '@/utils/auth'

const tenantEnable = import.meta.env.VITE_APP_TENANT_ENABLE

export const buildSseHeaders = () => {
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    Accept: 'text/event-stream'
  }
  const token = getAccessToken()
  if (token) {
    headers.Authorization = `Bearer ${token}`
  }
  if (tenantEnable && tenantEnable === 'true') {
    const tenantId = getTenantId()
    if (tenantId) {
      headers['tenant-id'] = String(tenantId)
    }
    const visitTenantId = getVisitTenantId()
    if (headers.Authorization && visitTenantId) {
      headers['visit-tenant-id'] = String(visitTenantId)
    }
  }
  return headers
}

export const validateSseHandshake = async (response: Response) => {
  const contentType = (response.headers.get('content-type') || '').toLowerCase()
  if (response.ok && contentType.includes('text/event-stream')) {
    return
  }

  let errorMessage = `流式请求失败（HTTP ${response.status}）`
  try {
    const json = await response.clone().json()
    errorMessage = json?.msg || json?.message || json?.error || json?.data?.msg || errorMessage
  } catch (jsonError) {
    const text = await response.clone().text()
    if (text) {
      errorMessage = text
    }
  }
  throw new Error(errorMessage)
}
