<?php
declare(strict_types=1);

namespace DMRS\MBS\Api\License;

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

/**
 * File Path: includes/api/license/class-mbs-license-registration.php
 *
 * License Registration Handler
 *
 * Handles the initial free-key registration request (first-contact, no HMAC).
 * This is the only license endpoint that does not use HMAC per the API contract
 * in Doc 0d and SECURITY.md.
 *
 * @package MyBookShowroom
 * @subpackage API\License
 * @since 1.0.0
 */

use WP_Error;

/**
 * Class MBS_License_Registration
 */
final class MBS_License_Registration {

	private MBS_License_Credentials $credentials;

	public function __construct() {
		$this->credentials = new MBS_License_Credentials();
	}

	/**
	 * Register a free license key with the API server.
	 *
	 * Called when an admin enters their email address to obtain a free key.
	 * The server creates a FREE license, emails the key, and returns it in
	 * the response body (one-time delivery per SECURITY.md).
	 *
	 * On success, the key is stored via MBS_License_Credentials so the admin
	 * does not need to manually paste it into the activate field.
	 *
	 * @param string $email Admin email address.
	 * @return array|WP_Error On success: array with at minimum 'license_key'. On failure: WP_Error.
	 */
	public function register( string $email ): array|WP_Error {
		$email = sanitize_email( $email );
		if ( ! is_email( $email ) ) {
			return new WP_Error( 'invalid_email', __( 'Please enter a valid email address.', 'my-book-showroom' ) );
		}

		$request_body = array(
			'email'          => $email,
			'domain'         => wp_parse_url( home_url(), PHP_URL_HOST ) ?: '',
			'plugin_version' => defined( 'MBS_VERSION' ) ? MBS_VERSION : '1.0.0',
			'wp_version'     => get_bloginfo( 'version' ),
			'php_version'    => PHP_VERSION,
		);

		$start    = microtime( true );
		$response = wp_remote_post( MBS_API_BASE . '/license/register', array(
			'headers' => array( 'Content-Type' => 'application/json' ),
			'body'    => wp_json_encode( $request_body ),
			'timeout' => 15,
		) );
		MBS_License_Request_Log::log_and_return( 'register', $request_body, $response, microtime( true ) - $start );

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$http_code = wp_remote_retrieve_response_code( $response );
		$data      = json_decode( wp_remote_retrieve_body( $response ), true );

		// B-003: Accept both 201 (new registration) and 200 (re-registration —
		// email already registered, key re-sent). Previously only 201 was accepted,
		// so admins who re-submitted their email saw a failure message even though
		// the server had successfully queued a key re-delivery email.
		if ( ! in_array( $http_code, array( 200, 201 ), true ) || empty( $data['success'] ) ) {
			$error_code = $data['error_code'] ?? 'registration_failed';
			$message    = $data['message']    ?? __( 'Free key registration failed. Please try again.', 'my-book-showroom' );
			return new WP_Error( $error_code, $message );
		}

		return $data;
	}
}
