import { apiClient } from './client';
import type {
  SatSyncJob,
  SatSyncStatusResponse,
  SatSyncHistoryResponse,
  StartSyncRequest,
  StartSyncResponse,
} from '@horux/shared';

export async function startSync(data?: StartSyncRequest, contribuyenteId?: string | null): Promise<StartSyncResponse> {
  const response = await apiClient.post<StartSyncResponse>('/sat/sync', {
    ...data,
    contribuyenteId: contribuyenteId || undefined,
  });
  return response.data;
}

export async function getSyncStatus(contribuyenteId?: string | null): Promise<SatSyncStatusResponse> {
  const response = await apiClient.get<SatSyncStatusResponse>('/sat/sync/status', {
    params: { contribuyenteId: contribuyenteId || undefined },
  });
  return response.data;
}

export async function getSyncHistory(page: number = 1, limit: number = 10, contribuyenteId?: string | null): Promise<SatSyncHistoryResponse> {
  const response = await apiClient.get<SatSyncHistoryResponse>('/sat/sync/history', {
    params: { page, limit, contribuyenteId: contribuyenteId || undefined },
  });
  return response.data;
}

export async function getSyncJob(id: string): Promise<SatSyncJob> {
  const response = await apiClient.get<SatSyncJob>(`/sat/sync/${id}`);
  return response.data;
}

export async function retrySync(id: string): Promise<StartSyncResponse> {
  const response = await apiClient.post<StartSyncResponse>(`/sat/sync/${id}/retry`);
  return response.data;
}

export async function getCronInfo(): Promise<{ scheduled: boolean; expression: string; timezone: string }> {
  const response = await apiClient.get('/sat/cron');
  return response.data;
}

export async function runCron(): Promise<{ message: string }> {
  const response = await apiClient.post('/sat/cron/run');
  return response.data;
}
