import { apiClient } from './client';
import { Purchase, Paginated, PurchaseFilters } from '@/types/purchase';

const buildPurchaseQuery = (filters: PurchaseFilters): string => {
    const params = new URLSearchParams();

    if (filters.email) params.append('email', filters.email);
    if (filters.mobile) params.append('mobile', filters.mobile);
    if (filters.package_name) params.append('package_name', filters.package_name);
    if (filters.gateway) params.append('gateway', filters.gateway);
    if (filters.status !== undefined && filters.status !== null) {
        params.append('status', String(filters.status));
    }
    if (filters.product_id !== undefined && filters.product_id !== null) {
        params.append('product_id', String(filters.product_id));
    }
    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.per_page) params.append('per_page', String(filters.per_page));
    if (filters.page) params.append('page', String(filters.page));

    return params.toString();
};

export const purchasesApi = {
    // List all subscription purchases with optional filters
    getPurchases: async (filters: PurchaseFilters, token: string): Promise<Paginated<Purchase>> => {
        const qs = buildPurchaseQuery(filters);
        return apiClient.get<Paginated<Purchase>>(`/admin/purchases${qs ? `?${qs}` : ''}`, token);
    },

    // Fetch ALL purchases matching the filters (used by the accounting section).
    // Learns the total from page 1, then fetches the remaining pages concurrently.
    getAllPurchases: async (filters: PurchaseFilters, token: string): Promise<Purchase[]> => {
        const perPage = filters.per_page || 500;
        const first = await purchasesApi.getPurchases({ ...filters, per_page: perPage, page: 1 }, token);

        const all = new Map<number, Purchase>();
        first.data.forEach((p) => all.set(p.id, p));

        const lastPage = first.last_page ?? 1;
        if (lastPage > 1) {
            const pages: number[] = [];
            for (let page = 2; page <= lastPage; page++) pages.push(page);

            // Fetch in small concurrent batches to avoid hammering the API
            const batchSize = 4;
            for (let i = 0; i < pages.length; i += batchSize) {
                const batch = pages.slice(i, i + batchSize);
                const results = await Promise.all(
                    batch.map((page) => purchasesApi.getPurchases({ ...filters, per_page: perPage, page }, token))
                );
                results.forEach((res) => res.data.forEach((p) => all.set(p.id, p)));
            }
        }

        return Array.from(all.values());
    },
};
