import { apiClient } from './client';

/**
 * API-клиент исторической миграции лидов (ТЗ §6).
 * Эндпоинты: POST/GET /api/imports, /api/imports/unknown-statuses, /api/imports/unknown-statuses/resolve.
 */

export interface ImportLogResource {
    id: number;
    filename: string;
    status: 'pending' | 'processing' | 'done' | 'failed';
    rows_total: number;
    rows_added: number;
    rows_updated: number;
    rows_skipped: number;
    unknown_statuses_count: number;
    dry_run: boolean;
    error_message: string | null;
    started_at: string | null;
    finished_at: string | null;
}

export interface UnknownStatus {
    id: number;
    status_ru: string;
    occurrences: number;
}

export interface StatusMapping {
    status_ru: string;
    slug: string;
}

/** POST /api/imports — загрузить CSV. */
export async function uploadImport(file: File, dryRun = false): Promise<ImportLogResource> {
    const form = new FormData();
    form.append('file', file);
    if (dryRun) {
        form.append('dry_run', '1');
    }
    const { data } = await apiClient.post<{ data: ImportLogResource }>('/api/imports', form);
    return data.data;
}

/** GET /api/imports — история импортов. */
export async function listImports(): Promise<ImportLogResource[]> {
    const { data } = await apiClient.get<{ data: ImportLogResource[] }>('/api/imports');
    return data.data;
}

/** GET /api/imports/{id} — прогресс одного импорта. */
export async function getImport(id: number): Promise<ImportLogResource> {
    const { data } = await apiClient.get<{ data: ImportLogResource }>(`/api/imports/${id}`);
    return data.data;
}

/** GET /api/imports/unknown-statuses — незамапленные статусы. */
export async function getUnknownStatuses(): Promise<UnknownStatus[]> {
    const { data } = await apiClient.get<{ data: UnknownStatus[] }>('/api/imports/unknown-statuses');
    return data.data;
}

/** POST /api/imports/unknown-statuses/resolve — сохранить маппинг. */
export async function resolveUnknownStatuses(mappings: StatusMapping[]): Promise<void> {
    await apiClient.post('/api/imports/unknown-statuses/resolve', { mappings });
}
