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

const BASE_URL = '/api/product-editor-audit-log';

export interface ProductEditorAuditLogEntry {
  user_id: number;
  username?: string;
  pid: number;
  action: 'product_edit' | 'image_changes' | 'taxonomy_set';
  request_payload: unknown;
  target_endpoint?: string;
  success: boolean;
  response_payload?: unknown;
  error_message?: string;
  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 editing flow.
 */
export async function createProductEditorAuditLog(entry: ProductEditorAuditLogEntry): 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 editor flow
    console.error('Failed to write product editor audit log:', error);
  }
}
