<?php

declare(strict_types=1);

namespace App\Services;

final class SignatureService
{
    private string $privateKey;

    private string $publicKey;

    public function __construct()
    {
        $this->privateKey =
            BASE_PATH . '/storage/keys/update_private.key';

        $this->publicKey =
            BASE_PATH . '/storage/keys/update_public.key';
    }

    public function generate(): void
    {
        if (
            is_file($this->privateKey) &&
            is_file($this->publicKey)
        ) {
            return;
        }

        $pair = sodium_crypto_sign_keypair();

        file_put_contents(
            $this->privateKey,
            sodium_crypto_sign_secretkey($pair)
        );

        file_put_contents(
            $this->publicKey,
            sodium_crypto_sign_publickey($pair)
        );
    }

    public function sign(string $file): string
    {
        $this->generate();

        $secret =
            file_get_contents($this->privateKey);

        $signature =
            sodium_crypto_sign_detached(
                file_get_contents($file),
                $secret
            );

        return base64_encode($signature);
    }

    public function verify(
        string $file,
        string $signature
    ): bool {

        $public =
            file_get_contents($this->publicKey);

        return sodium_crypto_sign_verify_detached(
            base64_decode($signature),
            file_get_contents($file),
            $public
        );
    }
}