import { apiClient, ensureCsrfCookie } from './client';

/**
 * In-app уведомления для bell-icon UI (schema v8.10).
 *
 * Все endpoint'ы под Sanctum SPA auth — для незалогиненных вернётся 401.
 * Mutating-вызовы (mark-read/mark-all-read/destroy) делают ensureCsrfCookie().
 */

type NotificationEvent =
    | 'new_lead'
    | 'low_balance'
    | 'zero_balance'
    | 'topup_success'
    | 'invoice_paid'
    | 'new_device_login'
    | 'marketing'
    | 'project_rule';

export interface ApiInAppNotification {
    id: number;
    event: NotificationEvent;
    title: string;
    body: string | null;
    deal_id: number | null;
    payload: Record<string, unknown>;
    read_at: string | null;
    created_at: string | null;
}

export interface ListNotificationsResponse {
    items: ApiInAppNotification[];
    unread_count: number;
    total: number;
}

export interface ListNotificationsParams {
    unreadOnly?: boolean;
    limit?: number;
}

export async function listNotifications(params: ListNotificationsParams = {}): Promise<ListNotificationsResponse> {
    const { data } = await apiClient.get<ListNotificationsResponse>('/api/notifications', {
        params: {
            unread_only: params.unreadOnly ? 1 : undefined,
            limit: params.limit,
        },
    });
    return data;
}

export async function markNotificationRead(id: number): Promise<{ id: number; read_at: string | null }> {
    await ensureCsrfCookie();
    const { data } = await apiClient.patch<{ id: number; read_at: string | null }>(`/api/notifications/${id}/read`);
    return data;
}

export async function markAllNotificationsRead(): Promise<{ updated: number }> {
    await ensureCsrfCookie();
    const { data } = await apiClient.post<{ updated: number }>('/api/notifications/mark-all-read');
    return data;
}

export async function deleteNotification(id: number): Promise<void> {
    await ensureCsrfCookie();
    await apiClient.delete(`/api/notifications/${id}`);
}
