'use client'

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:4000/api/v1'

export interface SavedCompany {
  id: string
  brand?: {
    displayName: string
    subdomain: string
    logoUrl?: string | null
  } | null
}

export interface RenterProfile {
  id: string
  firstName: string
  lastName: string
  email: string
  phone?: string | null
  preferredLocale?: string
  preferredCurrency?: string
  emailVerified?: boolean
  savedCompanies?: SavedCompany[]
}

export interface RenterPreference {
  notificationType: string
  channel: string
  enabled: boolean
}

export interface RenterNotification {
  id: string
  title: string
  body: string
  type: string
  status: string
  readAt: string | null
  createdAt: string
}

export class RenterAuthError extends Error {
  constructor(message = 'Authentication required') {
    super(message)
    this.name = 'RenterAuthError'
  }
}

async function renterFetch<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    ...init,
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      ...(init?.headers ?? {}),
    },
  })

  const json = await res.json().catch(() => null)
  if (res.status === 401) {
    throw new RenterAuthError()
  }
  if (!res.ok) throw new Error(json?.message ?? 'Request failed')
  return (json?.data ?? json) as T
}

export function clearRenterSession() {
  void fetch(`${API_BASE}/auth/renter/logout`, { method: 'POST', credentials: 'include' })
}

export function loadRenterProfile() {
  return renterFetch<RenterProfile>('/auth/renter/me')
}

export function updateRenterProfile(body: Partial<RenterProfile>) {
  return renterFetch<RenterProfile>('/auth/renter/me', {
    method: 'PATCH',
    body: JSON.stringify(body),
  })
}

export function loadRenterNotifications() {
  return renterFetch<RenterNotification[]>('/notifications/renter')
}

export function markRenterNotificationRead(id: string) {
  return renterFetch<{ success: boolean }>(`/notifications/renter/${id}/read`, {
    method: 'POST',
  })
}

export function markAllRenterNotificationsRead() {
  return renterFetch<{ success: boolean }>('/notifications/renter/read-all', {
    method: 'POST',
  })
}

export function loadRenterPreferences() {
  return renterFetch<RenterPreference[]>('/notifications/renter/preferences')
}

export function updateRenterPreferences(body: RenterPreference[]) {
  return renterFetch<{ success: boolean }>('/notifications/renter/preferences', {
    method: 'PATCH',
    body: JSON.stringify(body),
  })
}
