import apiClient from './client'
import type {
  ChannelTestResult,
  NotificationChannelCreate,
  NotificationChannelListResponse,
  NotificationChannelResponse,
  NotificationChannelUpdate,
  NotificationLogListResponse,
  NotificationRuleCreate,
  NotificationRuleListResponse,
  NotificationRuleResponse,
  NotificationRuleUpdate,
} from '@/types/api.types'

export const notificationsApi = {
  // ── Channels ───────────────────────────────────────────────────────────────

  /** Crea un canale di notifica. */
  createChannel: (data: NotificationChannelCreate) =>
    apiClient
      .post<NotificationChannelResponse>('/notifications/channels', data)
      .then((r) => r.data),

  /** Lista canali. */
  listChannels: (params?: { page?: number; page_size?: number }) =>
    apiClient
      .get<NotificationChannelListResponse>('/notifications/channels', { params })
      .then((r) => r.data),

  /** Dettaglio canale. */
  getChannel: (id: string) =>
    apiClient
      .get<NotificationChannelResponse>(`/notifications/channels/${id}`)
      .then((r) => r.data),

  /** Aggiorna canale. */
  updateChannel: (id: string, data: NotificationChannelUpdate) =>
    apiClient
      .patch<NotificationChannelResponse>(`/notifications/channels/${id}`, data)
      .then((r) => r.data),

  /** Elimina canale. */
  deleteChannel: (id: string) => apiClient.delete(`/notifications/channels/${id}`),

  /** Test canale. */
  testChannel: (id: string) =>
    apiClient
      .post<ChannelTestResult>(`/notifications/channels/${id}/test`)
      .then((r) => r.data),

  // ── Rules ──────────────────────────────────────────────────────────────────

  /** Crea una regola. */
  createRule: (data: NotificationRuleCreate) =>
    apiClient
      .post<NotificationRuleResponse>('/notifications/rules', data)
      .then((r) => r.data),

  /** Lista regole. */
  listRules: (params?: { channel_id?: string; page?: number; page_size?: number }) =>
    apiClient
      .get<NotificationRuleListResponse>('/notifications/rules', { params })
      .then((r) => r.data),

  /** Aggiorna regola. */
  updateRule: (id: string, data: NotificationRuleUpdate) =>
    apiClient
      .patch<NotificationRuleResponse>(`/notifications/rules/${id}`, data)
      .then((r) => r.data),

  /** Elimina regola. */
  deleteRule: (id: string) => apiClient.delete(`/notifications/rules/${id}`),

  // ── Logs ───────────────────────────────────────────────────────────────────

  /** Lista log notifiche. */
  listLogs: (params?: { channel_id?: string; page?: number; page_size?: number }) =>
    apiClient
      .get<NotificationLogListResponse>('/notifications/logs', { params })
      .then((r) => r.data),
}
