import { apiClient } from './client';
import type { FielStatus, FielUploadRequest } from '@horux/shared';

/**
 * FIEL API — contribuyente-aware for despachos.
 * If contribuyenteId is provided, uses per-contribuyente endpoints (tenant BD).
 * Otherwise, uses legacy tenant-level endpoints (central BD).
 */

export async function uploadFiel(data: FielUploadRequest, contribuyenteId?: string | null): Promise<{ message: string; status: FielStatus }> {
  if (contribuyenteId) {
    const response = await apiClient.post(`/contribuyentes/${contribuyenteId}/fiel`, data);
    return response.data;
  }
  const response = await apiClient.post('/fiel/upload', data);
  return response.data;
}

export async function getFielStatus(contribuyenteId?: string | null): Promise<FielStatus> {
  if (contribuyenteId) {
    const response = await apiClient.get<FielStatus>(`/contribuyentes/${contribuyenteId}/fiel/status`);
    return response.data;
  }
  const response = await apiClient.get<FielStatus>('/fiel/status');
  return response.data;
}

export async function deleteFiel(contribuyenteId?: string | null): Promise<void> {
  if (contribuyenteId) {
    // Try per-contribuyente delete first, then legacy as fallback
    try {
      await apiClient.delete(`/contribuyentes/${contribuyenteId}/fiel`);
      return;
    } catch {
      // Fallback to legacy if per-contribuyente endpoint doesn't exist
      try { await apiClient.delete('/fiel'); } catch { /* ignore */ }
      return;
    }
  }
  await apiClient.delete('/fiel');
}
