<?php
/**
 * Formatter service for PickupExceptions into WP_Error objects.
 *
 * @package    NovaPostWoocommerce
 * @subpackage Services
 */

namespace NovaPostForWoocommerce\Services;

use NovaPostForWoocommerce\Exceptions\PickupException;
use WP_Error;

/**
 * Converts PickupException into a frontend-friendly WP_Error.
 */
class PickupErrorFormatter {

    /**
     * Format a PickupException into a WP_Error.
     *
     * @param PickupException $e            The exception to format.
     * @param string          $default_code Optional error code for WP_Error.
     * @return WP_Error The formatted WP_Error.
     */
    public static function format( PickupException $e, string $default_code = PickupException::PICKUP_CREATION_FAILED ): WP_Error {
        $data   = $e->get_data();
        $errors = array();

        if ( ! empty( $data['errors'] ) && is_array( $data['errors'] ) ) {
            foreach ( $data['errors'] as $key => $value ) {
                $errors[] = is_string( $key ) ? "{$key}: {$value}" : (string) $value;
            }
        }

        $message = $errors[0] ?? $e->getMessage() ?? 'Validation error';

        return new WP_Error(
            $default_code,
            $message,
            array(
                'errors' => $errors,
                'status' => $data['status'] ?? 422,
            )
        );
    }
}
