/**
 * Patient activity feed — pulls a merged stream from the backend. Stays
 * permissive on the response shape so we can swap data sources without
 * touching the UI.
 */
export type ActivityKind =
  | 'appointment'
  | 'prescription'
  | 'triage'
  | 'feedback'
  | 'package';

export interface ActivityItem {
  id: string;
  kind: ActivityKind;
  title: string;
  description?: string | null;
  occurredAt: string;
  href?: string | null;
}

export class ActivityClientError extends Error {
  constructor(message: string, readonly statusCode: number) {
    super(message);
    this.name = 'ActivityClientError';
  }
}

export const activityClient = {
  async list(): Promise<ActivityItem[]> {
    const res = await fetch('/api/me/activity', { cache: 'no-store' });
    if (!res.ok) {
      // 404 → endpoint not deployed yet; treat as empty rather than throwing.
      if (res.status === 404) return [];
      const j = (await res.json().catch(() => null)) as {
        message?: string;
      } | null;
      throw new ActivityClientError(
        j?.message ?? `Activity request failed (${res.status})`,
        res.status,
      );
    }
    return (await res.json()) as ActivityItem[];
  },
};
