<?php

declare(strict_types=1);

namespace PpPhp\Core\Crypto;

/**
 * The per-project field-encryption key (base64 of 32 random bytes).
 *
 * Generated ONCE and persisted at projects/<owner>/<slug>/config/encryption.key so
 * it is identical on every build and to the console — regenerating it would orphan
 * already-encrypted data. Lives on the server / in the built app config, never in
 * the database. Shared by the build (bakes it in as PP_ENC_KEY) and the console
 * "encrypt existing rows" migration (which needs the same key).
 */
final class ProjectKey
{
    public static function get(string $owner, string $slug): string
    {
        $owner = trim($owner);
        $slug  = trim($slug);
        $dir   = constant('BASE_PATH') . "/projects/{$owner}/{$slug}/config";
        $file  = $dir . '/encryption.key';

        if (is_file($file)) {
            $k = trim((string) file_get_contents($file));
            if ($k !== '') return $k;
        }
        if (!is_dir($dir)) @mkdir($dir, 0775, true);
        $k = base64_encode(random_bytes(32));
        @file_put_contents($file, $k);
        @chmod($file, 0600);
        return $k;
    }
}
