function getBaseUrl(): string {
  const base = (import.meta.env.VITE_API_BASE_URL as string | undefined) ?? ''
  return base.replace(/\/$/, '')
}

function joinUrl(base: string, path: string): string {
  if (!base) return path
  return `${base}${path.startsWith('/') ? '' : '/'}${path}`
}

export type ClinicApplicationRequest = {
  name: string
  email: string
  phone: string
  city: string
  address: string
}

export async function submitClinicApplication(payload: ClinicApplicationRequest): Promise<any> {
  const url = joinUrl(getBaseUrl(), '/api/clinic-applications')
  const res = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: JSON.stringify(payload),
  })

  const contentType = res.headers.get('content-type') || ''
  const data = contentType.includes('application/json') ? await res.json() : null

  if (!res.ok) {
    throw new Error(data?.error || `Failed to submit clinic application (${res.status})`)
  }

  return data
}
