<?php

namespace EasyLinkAutomations\HTTP;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * HTTP response builder for AJAX and REST API responses.
 *
 * Supports both WordPress AJAX (wp_send_json_success/error) and
 * REST API (WP_REST_Response) contexts.
 */
final class Response
{
    private array $data = [];
    private string $message = '';
    private bool $success = true;
    private int $statusCode = 200;

    private function __construct() {}

    /**
     * Create a success response.
     */
    public static function success(array $data = []): static
    {
        $response          = new static();
        $response->success = true;
        $response->data    = $data;

        return $response;
    }

    /**
     * Create an error response.
     */
    public static function error(string $message, int $statusCode = 400): static
    {
        $response             = new static();
        $response->success    = false;
        $response->message    = $message;
        $response->statusCode = $statusCode;

        return $response;
    }

    /**
     * Set the HTTP status code (chainable).
     */
    public function httpStatus(int $code): static
    {
        $this->statusCode = $code;

        return $this;
    }

    /**
     * Send the response.
     *
     * For REST API requests: returns a WP_REST_Response.
     * For AJAX requests: sends JSON via wp_send_json_* and exits.
     */
    public function send(): void
    {
        if (defined('REST_REQUEST') && REST_REQUEST) {
            // For REST context, this should not be called directly —
            // the router wraps the response. We still send valid JSON.
            if ($this->success) {
                wp_send_json($this->data, $this->statusCode);
            } else {
                wp_send_json(['message' => $this->message], $this->statusCode);
            }

            return;
        }

        if ($this->statusCode !== 200) {
            status_header($this->statusCode);
        }

        if ($this->success) {
            wp_send_json_success($this->data);
        } else {
            wp_send_json_error(['message' => $this->message], $this->statusCode);
        }
    }

    /**
     * Convert to a WP_REST_Response (used by the REST router).
     */
    public function toRestResponse(): \WP_REST_Response
    {
        if ($this->success) {
            return new \WP_REST_Response($this->data, $this->statusCode ?: 200);
        }

        return new \WP_REST_Response(['message' => $this->message], $this->statusCode ?: 400);
    }

    public function isSuccess(): bool
    {
        return $this->success;
    }

    public function getData(): array
    {
        return $this->data;
    }

    public function getMessage(): string
    {
        return $this->message;
    }

    public function getStatusCode(): int
    {
        return $this->statusCode;
    }
}
