<?php

namespace Waypoint\Agent\Monitor;

use Waypoint\Agent\Auth\Bearer_Auth;
use Waypoint\Agent\Auth\Hmac_Auth;
use Waypoint\Agent\Auth\Role_Manager;
use Waypoint\Agent\Base\Thing;

class Registration extends Thing {

	public function attach_hooks(): void {
		add_action( WAYPOINT_MONITOR_RETRY_HOOK, [ $this, 'register' ] );
		add_action( 'waypoint_monitor_daily_heartbeat', [ $this, 'register' ] );
	}

	public static function on_activate(): void {
		Role_Manager::register_role();

		// Seed the first super admin from existing admins if none assigned yet.
		if ( ! Role_Manager::has_any_super_admin() ) {
			$admins = get_users( [
				'role'    => 'administrator',
				'orderby' => 'ID',
				'order'   => 'ASC',
				'number'  => 1,
				'fields'  => 'ids',
			] );
			if ( ! empty( $admins ) ) {
				Role_Manager::assign( (int) $admins[0] );
			}
		}

		Role_Manager::assign_trusted_domain_users();

		( new Hmac_Auth() )->maybe_generate_key();
		( new Bearer_Auth() )->get_token();

		$registration = new self();
		$ok           = $registration->register();

		if ( ! $ok && ! wp_next_scheduled( WAYPOINT_MONITOR_RETRY_HOOK ) ) {
			wp_schedule_single_event( time() + HOUR_IN_SECONDS, WAYPOINT_MONITOR_RETRY_HOOK );
		}
		if ( ! wp_next_scheduled( 'waypoint_monitor_daily_heartbeat' ) ) {
			wp_schedule_event( time() + DAY_IN_SECONDS, 'daily', 'waypoint_monitor_daily_heartbeat' );
		}
	}

	public static function on_deactivate(): void {
		wp_clear_scheduled_hook( WAYPOINT_MONITOR_RETRY_HOOK );
		wp_clear_scheduled_hook( 'waypoint_monitor_daily_heartbeat' );
	}

	public function register(): bool {
		$payload = [
			'url'              => home_url(),
			'token'            => ( new Bearer_Auth() )->get_token(),
			'wp_version'       => get_bloginfo( 'version' ),
			'plugin_version'   => WAYPOINT_AGENT_VERSION,
			'site_admin_email' => get_bloginfo( 'admin_email' ),
		];

		$response = wp_remote_post(
			$this->api_url() . '/api/waypoint-monitor/register',
			[
				'timeout'     => 10,
				'redirection' => 2,
				'blocking'    => true,
				'headers'     => [
					'Content-Type' => 'application/json',
					'Accept'       => 'application/json',
				],
				'body'        => wp_json_encode( $payload ),
			]
		);

		if ( is_wp_error( $response ) ) {
			error_log( 'Waypoint Agent: registration failed — ' . $response->get_error_message() );
			return false;
		}
		$code = wp_remote_retrieve_response_code( $response );
		if ( $code < 200 || $code >= 300 ) {
			error_log( 'Waypoint Agent: registration returned HTTP ' . $code );
			return false;
		}
		update_option( WAYPOINT_MONITOR_OPTION_REGISTERED_AT, time(), false );
		return true;
	}

	private function api_url(): string {
		if ( defined( 'WAYPOINT_MONITOR_API_URL' ) && is_string( WAYPOINT_MONITOR_API_URL ) ) {
			return rtrim( WAYPOINT_MONITOR_API_URL, '/' );
		}
		return WAYPOINT_MONITOR_DEFAULT_API_URL;
	}
}
