/// Utilities for normalizing Supabase/PostgREST response shapes.
///
/// Supabase Dart responses can appear as Maps (legacy wrapper) or
/// PostgrestResponse-like objects (have `.error`, `.status`, `.statusText`).
/// Helpers here provide a single place to extract an error message safely so
/// callers don't accidentally call `[]` on non-Map objects.
library;

String? extractSupabaseError(dynamic res) {
  if (res == null) return null;
  if (res is Map) {
    final err = res['error'];
    if (err != null) {
      return err is Map ? (err['message'] ?? err.toString()) : err.toString();
    }
    if (res['status'] != null && res['status'] is int && res['status'] >= 400) {
      return res['message']?.toString() ??
          'Request failed with status ${res['status']}';
    }
    return null;
  }

  // Try PostgrestResponse-like fields via dynamic access (safe within try/catch).
  try {
    final err = (res as dynamic).error;
    if (err != null) {
      return err is Map ? (err['message'] ?? err.toString()) : err.toString();
    }
  } catch (_) {}
  try {
    final status = (res as dynamic).status;
    if (status != null && status >= 400) {
      final statusText = (res as dynamic).statusText;
      return statusText ?? 'Request failed with status $status';
    }
  } catch (_) {}
  return null;
}
