<?php

declare(strict_types=1);

namespace App\Services\QzTray;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Crypt;

final class KeyStorageService
{
    /**
     * Store the private key securely (encrypted) on disk.
     *
     * @param string $keyName
     * @param string $privateKeyPem
     * @return string The storage relative path to the key file.
     */
    public function storeKey(string $keyName, string $privateKeyPem): string
    {
        $dir = rtrim(config('qztray.storage_path', 'secure/qz'), '/');
        $filename = "{$dir}/{$keyName}_private.key";

        // Encrypt private key PEM data before saving to disk
        $encryptedData = Crypt::encryptString($privateKeyPem);

        Storage::disk('local')->put($filename, $encryptedData);

        return $filename;
    }

    /**
     * Retrieve and decrypt the private key from disk.
     *
     * @param string $path
     * @return string|null
     */
    public function retrieveKey(string $path): ?string
    {
        if (!Storage::disk('local')->exists($path)) {
            return null;
        }

        $encryptedData = Storage::disk('local')->get($path);

        try {
            return Crypt::decryptString($encryptedData);
        } catch (\Throwable $e) {
            return null;
        }
    }

    /**
     * Delete the private key file from disk.
     *
     * @param string $path
     * @return bool
     */
    public function deleteKey(string $path): bool
    {
        if (Storage::disk('local')->exists($path)) {
            return Storage::disk('local')->delete($path);
        }

        return false;
    }
}
