<?php
/**
 * Antara — move encrypted vault files to quarantine and reset internal master key.
 * Shared by install/recover.php and the vault-config-unreadable gate.
 */

declare(strict_types=1);

if (!defined('ANTARA_ROOT')) {
    define('ANTARA_ROOT', dirname(__DIR__, 2));
}

require_once __DIR__ . '/paths.php';
require_once __DIR__ . '/vault_state.php';

final class AntaraVaultQuarantine
{
    /**
     * Moves *.enc and *.lock to quarantine, moves install.lock, removes internal .master.key.
     *
     * @return array{ok: bool, errors: list<string>, quarantine_dir: ?string}
     */
    public static function executeFullVaultReset(): array
    {
        $errors = [];
        AntaraPaths::ensureDirs();
        $secure = AntaraPaths::secure();
        $quarantineName = gmdate('Ymd\THis\Z') . '-' . bin2hex(random_bytes(4));
        $qDir = $secure . DIRECTORY_SEPARATOR . 'quarantine' . DIRECTORY_SEPARATOR . $quarantineName;
        if (!@mkdir($qDir, 0700, true) && !is_dir($qDir)) {
            return [
                'ok' => false,
                'errors' => ['No se pudo preparar la carpeta de cuarentena; revisa permisos con quien administra el servidor.'],
                'quarantine_dir' => null,
            ];
        }

        foreach (AntaraVaultState::storeCiphertextPaths() as $src) {
            if (is_file($src)) {
                $dest = $qDir . DIRECTORY_SEPARATOR . basename($src);
                if (!@rename($src, $dest)) {
                    $errors[] = 'No se pudo apartar un bloque de datos cifrados; revisa permisos con quien administra el servidor.';
                }
            }
        }

        $lockGlob = glob($secure . DIRECTORY_SEPARATOR . '*.lock');
        if (is_array($lockGlob)) {
            foreach ($lockGlob as $lockPath) {
                if (!is_file($lockPath)) {
                    continue;
                }
                $dest = $qDir . DIRECTORY_SEPARATOR . basename($lockPath);
                if (!@rename($lockPath, $dest)) {
                    @unlink($lockPath);
                }
            }
        }

        $installLock = AntaraPaths::installLockFile();
        if ($errors === [] && is_file($installLock)) {
            $destLock = $qDir . DIRECTORY_SEPARATOR . 'install.lock';
            if (!@rename($installLock, $destLock)) {
                $errors[] = 'No se pudo completar un paso del reinicio; revisa permisos con quien administra el servidor.';
            }
        }

        $candidates = AntaraVaultState::masterKeyCandidatePaths();
        $internalKey = AntaraPaths::secure() . DIRECTORY_SEPARATOR . '.master.key';
        foreach ($candidates as $p) {
            if (basename($p) === '.master.key') {
                $internalKey = $p;
                break;
            }
        }
        if ($errors === [] && is_file($internalKey)) {
            @unlink($internalKey);
        }

        if ($errors === [] && is_file(AntaraPaths::recoveryAllowFile())) {
            @unlink(AntaraPaths::recoveryAllowFile());
        }

        return [
            'ok' => $errors === [],
            'errors' => $errors,
            'quarantine_dir' => $qDir,
        ];
    }
}
