/**
 * API client per la Dashboard e Reportistica (Fase 7).
 */

import { apiClient } from './client'

// ─── Tipi ─────────────────────────────────────────────────────────────────────

export interface KpiSummary {
  received_today: number
  sent_today: number
  received_7d: number
  sent_7d: number
  received_30d: number
  sent_30d: number
  anomalie_attive: number
  tasso_consegna: number
  caselle_in_errore: number
  messaggi_non_letti: number
  totale_messaggi: number
}

export interface DailyStat {
  day: string   // "YYYY-MM-DD"
  received: number
  sent: number
}

export interface OutboundStateStat {
  state: string
  count: number
}

export interface MailboxStat {
  mailbox_id: string
  email_address: string
  display_name: string | null
  status: string
  received_total: number
  sent_total: number
  anomalie: number
  non_letti: number
  last_sync_at: string | null
}

export interface ReportSummaryResponse {
  generated_at: string
  period_days: number
  kpi: KpiSummary
  daily_stats: DailyStat[]
  outbound_states: OutboundStateStat[]
  mailbox_stats: MailboxStat[]
}

// ─── API ──────────────────────────────────────────────────────────────────────

export const reportsApi = {
  /**
   * Recupera il riepilogo KPI + grafici per la dashboard.
   * @param days  Numero di giorni per la serie storica (default 7)
   */
  getSummary: async (days = 7): Promise<ReportSummaryResponse> => {
    const res = await apiClient.get<ReportSummaryResponse>('/reports/summary', {
      params: { days },
    })
    return res.data
  },

  /**
   * Scarica il report in formato CSV.
   * Il browser riceverà un file da scaricare.
   */
  exportCsv: (params?: {
    date_from?: string
    date_to?: string
    mailbox_id?: string
  }) => {
    const url = new URL('/api/v1/reports/export', window.location.origin)
    url.searchParams.set('format', 'csv')
    if (params?.date_from) url.searchParams.set('date_from', params.date_from)
    if (params?.date_to) url.searchParams.set('date_to', params.date_to)
    if (params?.mailbox_id) url.searchParams.set('mailbox_id', params.mailbox_id)
    return url.toString()
  },

  /**
   * Scarica il report in formato PDF.
   */
  exportPdf: (params?: {
    date_from?: string
    date_to?: string
  }) => {
    const url = new URL('/api/v1/reports/export', window.location.origin)
    url.searchParams.set('format', 'pdf')
    if (params?.date_from) url.searchParams.set('date_from', params.date_from)
    if (params?.date_to) url.searchParams.set('date_to', params.date_to)
    return url.toString()
  },
}
