import { API_ENDPOINTS } from '@/shared/constants/apiEndpoints';
import { api } from '@/shared/utils/api';
import {
  type NotificationChannelKey,
  type NotificationListResult,
  type NotificationPreference,
  parseNotificationPreferences,
  parseNotificationsList,
  parseUnreadCount,
} from '@/features/notifications/types/notification.types';

export interface FetchNotificationsParams {
  page?: number;
  per_page?: number;
}

export async function fetchNotifications(
  params: FetchNotificationsParams = {},
): Promise<NotificationListResult> {
  const search = new URLSearchParams();
  if (params.page) {
    search.set('page', String(params.page));
  }
  if (params.per_page) {
    search.set('per_page', String(params.per_page));
  }
  const query = search.toString();
  const raw: unknown = await api.get(
    `${API_ENDPOINTS.NOTIFICATIONS.LIST}${query ? `?${query}` : ''}`,
  );
  return parseNotificationsList(raw);
}

export async function fetchUnreadCount(): Promise<number> {
  const raw: unknown = await api.get(API_ENDPOINTS.NOTIFICATIONS.UNREAD_COUNT);
  return parseUnreadCount(raw);
}

export async function markNotificationRead(id: string): Promise<void> {
  await api.post(API_ENDPOINTS.NOTIFICATIONS.MARK_READ(id));
}

export async function markAllNotificationsRead(): Promise<void> {
  await api.post(API_ENDPOINTS.NOTIFICATIONS.MARK_ALL_READ);
}

export async function deleteNotification(id: string): Promise<void> {
  await api.delete(API_ENDPOINTS.NOTIFICATIONS.DELETE(id));
}

export async function fetchNotificationPreferences(): Promise<NotificationPreference[]> {
  const raw: unknown = await api.get(API_ENDPOINTS.NOTIFICATION_PREFERENCES.LIST);
  return parseNotificationPreferences(raw);
}

export async function updateNotificationPreferences(
  preferences: Array<{ notification_type: string; channels: NotificationChannelKey[] }>,
): Promise<void> {
  await api.put(API_ENDPOINTS.NOTIFICATION_PREFERENCES.UPDATE, { preferences });
}

export async function resetNotificationPreferences(): Promise<void> {
  await api.post(API_ENDPOINTS.NOTIFICATION_PREFERENCES.RESET);
}
