export interface Notification {
  id: string;
  restaurantId: string;
  userId?: string;
  type: string;
  title: string;
  message: string;
  isRead: boolean;
  link?: string;
  createdAt: string;
}

export interface NotificationListResponse {
  notifications: Notification[];
  unread: number;
  total: number;
  page: number;
  limit: number;
  pages: number;
}

function normalizeNotification(raw: Record<string, unknown>): Notification {
  return {
    id: String(raw.id ?? ''),
    restaurantId: String(raw.restaurant_id ?? raw.restaurantId ?? ''),
    userId: raw.user_id != null ? String(raw.user_id) : (raw.userId != null ? String(raw.userId) : undefined),
    type: String(raw.type ?? 'system'),
    title: String(raw.title ?? ''),
    message: String(raw.message ?? ''),
    isRead: Boolean(raw.is_read ?? raw.isRead ?? false),
    link: raw.link != null ? String(raw.link) : undefined,
    createdAt: String(raw.created_at ?? raw.createdAt ?? ''),
  };
}

async function apiFetch<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, { credentials: 'include', ...options });
  const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
  if (!res.ok) throw new Error((json.error as string) || `Request failed: ${res.status}`);
  return json as T;
}

export async function listNotifications(params: Record<string, string> = {}): Promise<NotificationListResponse> {
  const qs = new URLSearchParams(params).toString();
  const raw = await apiFetch<{ notifications: Record<string, unknown>[]; unread: number; total: number; page: number; limit: number; pages: number }>(`/api/notifications${qs ? '?' + qs : ''}`);
  return {
    notifications: (raw.notifications ?? []).map(normalizeNotification),
    unread: raw.unread ?? 0,
    total: raw.total,
    page: raw.page,
    limit: raw.limit,
    pages: raw.pages,
  };
}

export async function markNotificationRead(id: string): Promise<{ notification: Notification }> {
  const raw = await apiFetch<{ notification: Record<string, unknown> }>(`/api/notifications/${id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ is_read: true }),
  });
  return { notification: normalizeNotification(raw.notification) };
}

export async function markAllNotificationsRead(): Promise<{ updated: number }> {
  return apiFetch<{ updated: number }>('/api/notifications/read-all', { method: 'PATCH' });
}

export async function deleteNotification(id: string): Promise<{ success: boolean }> {
  return apiFetch<{ success: boolean }>(`/api/notifications/${id}`, { method: 'DELETE' });
}
