import { apiClient } from './api/client';
import { logger } from '@/utils/logger';

export interface Webhook {
    id: string;
    url: string;
    events: string[];
    status: 'active' | 'failed';
    lastTriggered: string;
    secret?: string;
    created_at: string;
}

export const webhookService = {
    list: async (): Promise<Webhook[]> => {
        try {
            const response = await apiClient.get<any[]>('/webhooks');
            return (response.data || []).map(hook => ({
                id: hook.id,
                url: hook.url,
                events: hook.events || [],
                status: hook.status || 'active',
                lastTriggered: hook.last_triggered || 'Never',
                created_at: hook.created_at,
            }));
        } catch (error) {
            logger.error('[Webhooks] Failed to list webhooks', { error });
            return [];
        }
    },

    create: async (url: string, events: string[] = ['*']): Promise<Webhook> => {
        const response = await apiClient.post<any>('/webhooks', {
            url,
            events,
        });
        return response.data;
    },

    delete: async (id: string): Promise<void> => {
        await apiClient.delete(`/webhooks/${id}`);
    },

    regenerateKey: async (id: string): Promise<{ api_key: string }> => {
        const response = await apiClient.post<{ data: { api_key: string } }>(`/webhooks/${id}/regenerate-key`);
        // APIClient might already unwrap the first level of "data"
        // If response.data is { api_key }, we return it.
        return response.data as any;
    }
};
