import axios, { type AxiosInstance } from 'axios'

export interface FhirBundleLink {
  relation: string
  url: string
}

export interface FhirBundleEntry {
  fullUrl?: string
  resource?: FhirResource
  search?: { mode?: string }
}

export interface FhirBundle {
  resourceType: 'Bundle'
  type?: string
  total?: number
  entry?: FhirBundleEntry[]
  link?: FhirBundleLink[]
}

export type FhirResource = Record<string, unknown> & {
  resourceType: string
  id?: string
}

const fhirClient: AxiosInstance = axios.create({
  baseURL: '/fhir',
  timeout: 30000,
  headers: {
    Accept: 'application/fhir+json',
  },
})

fhirClient.interceptors.request.use((config) => {
  const token = localStorage.getItem('vigilcare_token')
  if (token && config.headers) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

export async function fhirGet<T = unknown>(
  path: string,
  params?: Record<string, string | number | undefined>
): Promise<T> {
  const cleaned: Record<string, string | number> = {}
  if (params) {
    for (const [key, value] of Object.entries(params)) {
      if (value !== undefined && value !== '') {
        cleaned[key] = value
      }
    }
  }

  const response = await fhirClient.get<T>(path, { params: cleaned })
  return response.data
}

export function openFhirJsonInNewTab(data: unknown, filename = 'fhir-resource.json'): void {
  const blob = new Blob([JSON.stringify(data, null, 2)], {
    type: 'application/fhir+json',
  })
  const url = URL.createObjectURL(blob)
  const tab = window.open(url, '_blank')
  if (!tab) {
    URL.revokeObjectURL(url)
    return
  }
  tab.document.title = filename
  setTimeout(() => URL.revokeObjectURL(url), 60_000)
}
