import { apiClient } from './apiClient';

export interface ImportTask {
    id: string;
    sourcePath: string;
    targetGroupId?: string;
    targetGroupName?: string;
    scheduledAt?: string;
    status: 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'FAILED';
    logs?: string;
    embeddingModelId?: string;
    chunkSize?: number;
    chunkOverlap?: number;
    mode?: string;
    createdAt: string;
}

export const importService = {
    create: async (authToken: string, data: {
        sourcePath: string;
        targetGroupId?: string;
        targetGroupName?: string;
        embeddingModelId: string;
        scheduledAt?: string;
        chunkSize?: number;
        chunkOverlap?: number;
        mode?: string;
    }): Promise<ImportTask> => {
        const response = await apiClient.request('/import-tasks', {
            method: 'POST',
            body: JSON.stringify(data)
        });
        if (!response.ok) throw new Error('Failed to create import task');
        return response.json();
    },

    getAll: async (authToken: string, options: { page?: number; limit?: number } = {}): Promise<{ items: ImportTask[]; total: number; page: number; limit: number }> => {
        const queryParams = new URLSearchParams();
        if (options.page) queryParams.append('page', options.page.toString());
        if (options.limit) queryParams.append('limit', options.limit.toString());

        const queryString = queryParams.toString();
        const url = `/import-tasks${queryString ? `?${queryString}` : ''}`;

        const response = await apiClient.request(url, {});
        if (!response.ok) throw new Error('Failed to fetch import tasks');
        return response.json();
    },

    delete: async (authToken: string, id: string): Promise<void> => {
        const response = await apiClient.request(`/import-tasks/${id}`, {
            method: 'DELETE',
        });
        if (!response.ok) throw new Error('Failed to delete import task');
    }
};
