package com.example.petstoremobile.utils;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.example.petstoremobile.dtos.ErrorResponse;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import retrofit2.Response;

/**
 * Utility class for handling API error responses.
 */
public class ErrorUtils {
    private static final String TAG = "ErrorUtils";
    private static final Gson gson = new Gson();

    /**
     * Shows an error message to toast based on the response.
     */
    public static void showErrorMessage(Context context, Response<?> response, String defaultMessage) {
        Toast.makeText(context, getErrorMessage(response, defaultMessage), Toast.LENGTH_LONG).show();
    }

    /**
     * Extracts a user-friendly error message from the response body or status code.
     */
    public static String getErrorMessage(Response<?> response, String defaultMessage) {
        if (response == null) return defaultMessage;

        try {
            if (response.errorBody() != null) {
                String errorJson = response.errorBody().string();
                Log.e(TAG, "Full Error JSON: " + errorJson);
                ErrorResponse errorResponse = gson.fromJson(errorJson, ErrorResponse.class);
                if (errorResponse != null && errorResponse.getMessage() != null) {
                    return errorResponse.getMessage();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error parsing error body", e);
        }

        // Handle specific status codes if no message was provided by the API
        switch (response.code()) {
            case 401: return "Unauthorized. Please login again.";
            case 403: return "Access denied.";
            case 404: return "Resource not found.";
            case 500: return "Internal server error. Please try again later.";
            case 503: return "Service unavailable. The server might be down.";
            default: return defaultMessage + " (Code: " + response.code() + ")";
        }
    }

    /**
     * Converts a Throwable (from onFailure) into a user-friendly network error message.
     */
    public static String getFailureMessage(Throwable t) {
        if (t instanceof UnknownHostException || t instanceof ConnectException) {
            return "No internet connection. Please check your settings.";
        } else if (t instanceof SocketTimeoutException) {
            return "The connection timed out. Please try again.";
        } else if (t instanceof IOException) {
            return "Network error occurred. Please try again.";
        } else {
            return "An unexpected error occurred: " + t.getLocalizedMessage();
        }
    }
}
