import { apiFetch } from '@/utils/api';
/**
 * Import Audit Log API Service
 *
 * Logs every product import submission to a permanent audit trail.
 * Fire-and-forget by default — callers should not block on the result.
 */

const BASE_URL = '/api/import-audit-log';

export interface ImportAuditLogEntry {
  user_id: number;
  username?: string;
  product_count: number;
  request_payload: unknown;
  environment: 'dev' | 'prod';
  target_endpoint?: string;
  use_test_data_source?: boolean;
  success: boolean;
  response_payload?: unknown;
  error_message?: string;
  created_count?: number;
  errored_count?: number;
  session_id?: number | null;
  duration_ms?: number | null;
}

/**
 * Send an audit log entry to the backend.
 * Designed to be fire-and-forget — errors are logged but never thrown
 * so that a logging failure never blocks the user's import flow.
 */
export async function createImportAuditLog(entry: ImportAuditLogEntry): Promise<void> {
  try {
    await apiFetch(BASE_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(entry),
    });
  } catch (error) {
    // Never throw — audit logging should not disrupt the import flow
    console.error('Failed to write import audit log:', error);
  }
}
