<?php
/**
 * SwapAds Error Response Builder
 *
 * Builds standardized error responses for the REST API.
 *
 * @package SwapAds\Shared
 * @since   1.0.0
 */

declare(strict_types=1);

namespace SwapAds\Shared\Errors;

use Ramsey\Uuid\Uuid;
use WP_REST_Response;

/**
 * Class ErrorResponse
 *
 * Centralized error response builder for all SwapAds endpoints.
 * Enforces the canonical response format (success, error_code, message, details, meta).
 *
 * @since 1.0.0
 */
final class ErrorResponse
{
    /**
     * Build a WP REST error response
     *
     * @param string $code       Canonical error code (see ErrorCode class).
     * @param string $message    Human-readable error message.
     * @param int    $httpStatus HTTP status code (default: 400).
     * @param array  $details    Additional error details (optional).
     *
     * @return WP_REST_Response Formatted error response.
     *
     * @since 1.0.0
     */
    public static function build(
        string $code,
        string $message,
        int $httpStatus = 400,
        array $details = []
    ): WP_REST_Response {
        return new WP_REST_Response([
            'success'    => false,
            'error_code' => $code,
            'message'    => $message,
            'details'    => $details,
            'meta'       => [
                'timestamp'  => gmdate('Y-m-d\TH:i:s\Z'),
                'request_id' => self::generateRequestId(),
            ],
        ], $httpStatus);
    }

    /**
     * Build a success response
     *
     * @param array $data  Response data payload.
     * @param int   $httpStatus HTTP status code (default: 200).
     *
     * @return WP_REST_Response Formatted success response.
     *
     * @since 1.0.0
     */
    public static function success(array $data, int $httpStatus = 200): WP_REST_Response
    {
        return new WP_REST_Response([
            'success' => true,
            'data'    => $data,
            'meta'    => [
                'timestamp'  => gmdate('Y-m-d\TH:i:s\Z'),
                'request_id' => self::generateRequestId(),
            ],
        ], $httpStatus);
    }

    /**
     * Generate a unique request ID
     *
     * Used for tracing and debugging.
     *
     * @return string UUID v4.
     *
     * @since 1.0.0
     */
    private static function generateRequestId(): string
    {
        return Uuid::uuid4()->toString();
    }
}
