import { apiClient, ensureCsrfCookie } from './client';

/**
 * Reports API (schema §13.5 report_jobs).
 *
 * Все endpoint'ы под Sanctum SPA auth. Mutating-вызовы (POST/DELETE)
 * делают ensureCsrfCookie().
 *
 * Backend status: pending|processing|done|failed (schema-канон).
 * UI mock использует queued|running|done|failed — конверсия в reportsMapper.
 */

export type ApiReportStatus = 'pending' | 'processing' | 'done' | 'failed';

type ApiReportType = 'deals_export' | 'managers_summary' | 'sources_summary' | 'billing_summary';

type ApiReportFormat = 'csv' | 'xlsx' | 'json' | 'pdf';

interface ApiReportParameters {
    format: ApiReportFormat;
    date_from: string;
    date_to: string;
    project_id?: number | null;
    manager_id?: number | null;
    retry_count?: number;
    retry_of?: number;
}

export interface ApiReportJob {
    id: number;
    type: ApiReportType;
    parameters: ApiReportParameters;
    status: ApiReportStatus;
    file_path: string | null;
    download_url: string | null;
    file_size: number | null;
    generation_seconds: number | null;
    error_message: string | null;
    created_at: string | null;
    finished_at: string | null;
    expires_at: string | null;
    is_expired: boolean;
    retry_count: number;
    retry_max: number;
}

interface ReportCounts {
    pending: number;
    processing: number;
    done: number;
    failed: number;
}

interface ReportQuota {
    active: number;
    max_active: number;
}

export interface ListReportJobsResponse {
    jobs: ApiReportJob[];
    total: number;
    limit: number;
    offset: number;
    counts: ReportCounts;
    quota: ReportQuota;
}

export interface ListReportJobsParams {
    status?: ApiReportStatus;
    limit?: number;
    offset?: number;
}

export async function listReportJobs(params: ListReportJobsParams = {}): Promise<ListReportJobsResponse> {
    const { data } = await apiClient.get<ListReportJobsResponse>('/api/reports/jobs', {
        params: {
            status: params.status,
            limit: params.limit,
            offset: params.offset,
        },
    });
    return data;
}

export interface CreateReportJobPayload {
    type: ApiReportType;
    format: ApiReportFormat;
    parameters: {
        date_from: string;
        date_to: string;
        project_id?: number | null;
        manager_id?: number | null;
    };
}

export async function createReportJob(payload: CreateReportJobPayload): Promise<ApiReportJob> {
    await ensureCsrfCookie();
    const { data } = await apiClient.post<{ job: ApiReportJob }>('/api/reports/jobs', payload);
    return data.job;
}

export async function retryReportJob(id: number): Promise<ApiReportJob> {
    await ensureCsrfCookie();
    const { data } = await apiClient.post<{ job: ApiReportJob }>(`/api/reports/jobs/${id}/retry`);
    return data.job;
}

export async function cancelReportJob(id: number): Promise<ApiReportJob> {
    await ensureCsrfCookie();
    const { data } = await apiClient.post<{ job: ApiReportJob }>(`/api/reports/jobs/${id}/cancel`);
    return data.job;
}

export async function deleteReportJob(id: number): Promise<void> {
    await ensureCsrfCookie();
    await apiClient.delete(`/api/reports/jobs/${id}`);
}
