import { apiClient } from './client';
import { AuthLogFilters, AuthStats, PaginatedAuthLogs } from '@/types/auth-log';

const buildAuthLogQuery = (filters: AuthLogFilters): string => {
    const params = new URLSearchParams();

    if (filters.event) params.append('event', filters.event);
    if (filters.mobile) params.append('mobile', filters.mobile);
    if (filters.email) params.append('email', filters.email);
    if (filters.package_name) params.append('package_name', filters.package_name);
    if (filters.success !== undefined) params.append('success', filters.success ? '1' : '0');
    if (filters.sms_only) params.append('sms_only', '1');
    if (filters.date_from) params.append('date_from', filters.date_from);
    if (filters.date_to) params.append('date_to', filters.date_to);
    if (filters.time_from) params.append('time_from', filters.time_from);
    if (filters.time_to) params.append('time_to', filters.time_to);
    if (filters.sms_unit_cost !== undefined) params.append('sms_unit_cost', String(filters.sms_unit_cost));
    if (filters.per_page) params.append('per_page', String(filters.per_page));
    if (filters.page) params.append('page', String(filters.page));

    return params.toString();
};

export const authLogsApi = {
    // Aggregated OTP/SMS and login stats for the analytics cards and chart
    getStats: async (filters: AuthLogFilters, token: string): Promise<AuthStats> => {
        const qs = buildAuthLogQuery(filters);
        return apiClient.get<AuthStats>(`/admin/auth-stats${qs ? `?${qs}` : ''}`, token);
    },

    // Raw paginated event log
    getLogs: async (filters: AuthLogFilters, token: string): Promise<PaginatedAuthLogs> => {
        const qs = buildAuthLogQuery(filters);
        return apiClient.get<PaginatedAuthLogs>(`/admin/auth-logs${qs ? `?${qs}` : ''}`, token);
    },
};
