import 'package:flutter/material.dart';

import 'package:pshared/api/responses/error/connectivity.dart';
import 'package:pshared/api/responses/error/server.dart';
import 'package:pshared/config/constants.dart';

import 'package:pweb/generated/i18n/app_localizations.dart';


class ErrorHandler {
  /// A mapping of server-side error codes to localized user-friendly messages.
  /// Update these keys to match the 'ErrorResponse.Error' field in your Go code.
  static Map<String, String> getErrorMessagesLocs(AppLocalizations locs) {
    return {
      'account_not_verified': locs.errorAccountNotVerified,
      'unauthorized': locs.errorLoginUnauthorized,
      'verification_token_not_found': locs.errorVerificationTokenNotFound,
      'user_already_registered': locs.errorDuplicateEmail,
      'internal_error': locs.errorInternalError,
      'invalid_target': locs.errorInvalidTarget,
      'pending_token_required': locs.errorPendingTokenRequired,
      'missing_destination': locs.errorMissingDestination,
      'missing_code': locs.errorMissingCode,
      'missing_session': locs.errorMissingSession,
      'token_expired': locs.errorTokenExpired,
      'code_attempts_exceeded': locs.errorCodeAttemptsExceeded,
      'too_many_requests': locs.errorTooManyRequests,

      'data_conflict': locs.errorDataConflict,
      'access_denied': locs.errorAccessDenied,
      'broken_payload': locs.errorBrokenPayload,
      'invalid_argument': locs.errorInvalidArgument,
      'broken_reference': locs.errorBrokenReference,
      'invalid_query_parameter': locs.errorInvalidQueryParameter,
      'not_implemented': locs.errorNotImplemented,
      'license_required': locs.errorLicenseRequired,
      'not_found': locs.errorNotFound,
      'name_missing': locs.errorNameMissing,
      'email_missing': locs.errorEmailMissing,
      'password_missing': locs.errorPasswordMissing,
      'email_not_registered': locs.errorEmailNotRegistered,
      'duplicate_email': locs.errorDuplicateEmail,
     };
  }

  static Map<String, String> getErrorMessages(BuildContext context) {
    return getErrorMessagesLocs(AppLocalizations.of(context)!);
  }

  /// Determine which handler to use based on the runtime type of [e].
  /// If no match is found, just return the error’s string representation.
  static String handleError(BuildContext context, Object e) {
    return handleErrorLocs(AppLocalizations.of(context)!, e);
  }

  static String handleErrorLocs(AppLocalizations locs, Object e) {
    final errorHandlers = <Type, String Function(Object)>{
      ErrorResponse: (ex) => _handleErrorResponseLocs(locs, ex as ErrorResponse),
      ConnectivityError: (ex) => _handleConnectivityErrorLocs(locs, ex as ConnectivityError),
    };

    return errorHandlers[e.runtimeType]?.call(e) ?? e.toString();
  }

  static String _handleErrorResponseLocs(AppLocalizations locs, ErrorResponse e) {
    if (e.source == 'user_already_registered') {
      return locs.errorDuplicateEmail;
    }
    final errorMessages = getErrorMessagesLocs(locs);
    // Return the localized message if we recognize the error key, else use the raw details
    return errorMessages[e.error] ?? e.details;
  }

  /// Handler for connectivity issues.
  static String _handleConnectivityErrorLocs(AppLocalizations locs, ConnectivityError e) {
    return locs.connectivityError(Constants.serviceUrl);
  }
}
