<?php

declare(strict_types=1);

namespace FormConnector\API\Endpoints;

use FormConnector\Features\License\License;
use FormConnector\Features\Homes\Homes;

/**
 * Startup REST API endpoint.
 *
 * Called once when the admin page loads. Validates the license against the
 * remote server and returns a combined payload so every tab has fresh data.
 */
class StartupEndpoints {

	private const NAMESPACE = 'fc/v1';

	/**
	 * Register startup route.
	 */
	public static function register(): void {
		register_rest_route(self::NAMESPACE, '/startup', [
			'methods'             => \WP_REST_Server::CREATABLE,
			'callback'            => [self::class, 'startup'],
			'permission_callback' => [self::class, 'permission_check'],
		]);
	}

	/**
	 * Permission check for admin-only endpoints.
	 */
	public static function permission_check(): bool {
		return current_user_can('manage_options');
	}

	/**
	 * Run startup checks.
	 *
	 * 1. Force-validates the license key with the remote server.
	 * 2. If valid, fetches fresh homes + subscription data.
	 * 3. Returns everything the frontend needs in one payload.
	 */
	public static function startup(\WP_REST_Request $request): \WP_REST_Response {
		$license = new License();
		$key     = $license->get_key();

		$payload = [
			'license'   => null,
			'homes'     => null,
			'warnings'  => [],
		];

		// ── No key configured — return minimal status ──
		if (empty($key)) {
			$payload['license'] = $license->get_status();
			return new \WP_REST_Response(['success' => true, 'data' => $payload], 200);
		}

		// ── Force-validate the license with the remote API ──
		$license->clear_validation_cache();
		$validation = $license->validate($key);

		// Always return fresh status after the validate call
		$payload['license'] = $license->get_status();

		if (!$validation['success']) {
			$payload['warnings'][] = [
				'type'    => 'license',
				'message' => $validation['error'] ?? __('License validation failed.', 'form-connector'),
			];
			// Still return 200 so the frontend can render the state
			return new \WP_REST_Response(['success' => true, 'data' => $payload], 200);
		}

		// ── License is valid — fetch fresh homes data ──
		$homes        = new Homes();
		$homes_result = $homes->get_homes(true); // force refresh from API

		if ($homes_result['success']) {
			$seat_info   = $homes->get_active_home_ids();
			$homes_list  = $homes_result['data']['homes'] ?? [];
			$subscription = Homes::normalize_subscription($homes_result['data']['subscription'] ?? null, count($homes_list));

			$payload['homes'] = [
				'homes'        => $homes_list,
				'count'        => count($homes_list),
				'subscription' => $subscription,
				'seatStatus'   => [
					'isOverLimit'    => $seat_info['is_over_limit'],
					'overLimitCount' => $seat_info['over_limit_count'],
					'activeHomeIds'  => $seat_info['active_home_ids'],
					'isUnlimited'    => $seat_info['is_unlimited'],
				],
			];
		} else {
			$payload['warnings'][] = [
				'type'    => 'homes',
				'message' => $homes_result['message'] ?? __('Failed to fetch homes.', 'form-connector'),
			];
		}

		return new \WP_REST_Response(['success' => true, 'data' => $payload], 200);
	}
}
