<?php

namespace CaptureRelay;

use WP_Error;
use WP_REST_Request;

/**
 * Integration boundary for Apple App Attest and Google Play Integrity.
 * Verification is intentionally server-side and never relies on a secret
 * embedded in the distributable app.
 */
final class AppProof
{
    public static function required(): bool
    {
        return (bool) apply_filters('capture_relay_app_proof_required', false);
    }

    public static function available(): bool
    {
        return has_filter('capture_relay_verify_app_proof');
    }

    public static function verify(WP_REST_Request $request, array $input, string $platform): true|WP_Error
    {
        if (!self::required()) {
            return true;
        }
        $proof = trim((string) $request->get_header('x-capturerelay-app-proof'));
        if ($proof === '' || strlen($proof) > 16384) {
            return new WP_Error('capture_relay_app_proof_required', __('This website requires verification from the official CaptureRelay app.', 'capture-relay'), ['status' => 403]);
        }
        $verified = self::available()
            ? apply_filters('capture_relay_verify_app_proof', null, $proof, $platform, $input, $request)
            : null;
        if ($verified === true) {
            return true;
        }
        Log::write('app_proof_rejected', 'A connection request failed official-app verification.', [], 'warning');
        if ($verified === null) {
            return new WP_Error('capture_relay_app_proof_unavailable', __('Official-app verification is temporarily unavailable.', 'capture-relay'), ['status' => 503]);
        }
        return new WP_Error('capture_relay_app_proof_invalid', __('The connection request did not come from a verified CaptureRelay app.', 'capture-relay'), ['status' => 403]);
    }
}
