import type { ApiResponse } from '@alqove/types';
import type { AlqoveClient } from '../client';

export interface NotificationInboxItem {
  id: string;
  type: string;
  title: string;
  body: string;
  cta_url: string;
  icon: 'package' | 'truck' | 'check' | 'alert' | 'x' | 'package-return' | 'message';
  context_type: 'order' | 'purchase';
  context_id: string;
  read_at: string | null;
  created_at: string;
}

export interface NotificationInboxMeta {
  unread_count: number;
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
}

/**
 * Inbox list response — `data` and `meta` are top-level (no extra wrap).
 * This shape differs from the standard {data: T} pattern: the body itself
 * IS the page, with `meta` carrying pagination + unread_count alongside.
 */
export interface NotificationInboxList {
  data: NotificationInboxItem[];
  meta: NotificationInboxMeta;
}

export interface NotificationUnreadCount {
  unread_count: number;
}

export interface NotificationPreference {
  channel: 'email' | 'push';
  category: 'orders' | 'shipping' | 'payouts' | 'promotions' | 'price_drops' | 'account';
  enabled: boolean;
  is_transactional: boolean;
}

export interface NotificationPreferencesUpdate {
  preferences: Array<Pick<NotificationPreference, 'channel' | 'category' | 'enabled'>>;
}

export function createNotificationEndpoints(client: AlqoveClient) {
  return {
    list(params?: {
      filter?: 'all' | 'unread';
      // Single category, OR a comma-separated list (admin inbox passes
      // multiple admin-scoped categories at once).
      category?:
        | 'orders'
        | 'shipping'
        | 'payouts'
        | 'system'
        | 'promotions'
        | 'price_drops'
        | 'account'
        | 'disputes'
        | 'account_admin'
        | string;
      per_page?: number;
      page?: number;
    }) {
      return client.get<NotificationInboxList>(
        '/v1/me/notifications',
        params as Record<string, string> | undefined,
      );
    },
    unreadCount() {
      return client.get<ApiResponse<NotificationUnreadCount>>(
        '/v1/me/notifications/unread-count',
      );
    },
    markRead(id: string) {
      return client.patch<void>(`/v1/me/notifications/${id}/read`, {});
    },
    markAllRead() {
      return client.post<ApiResponse<{ updated: number }>>(
        '/v1/me/notifications/mark-all-read',
        {},
      );
    },
    listPreferences() {
      return client.get<ApiResponse<NotificationPreference[]>>(
        '/v1/me/notification-preferences',
      );
    },
    updatePreferences(body: NotificationPreferencesUpdate) {
      return client.patch<ApiResponse<NotificationPreference[]>>(
        '/v1/me/notification-preferences',
        body,
      );
    },
  };
}
