<?php

namespace App\Support\Safety;

use Symfony\Component\Console\Exception\RuntimeException;

class DestructiveDbGuard
{
    public function check(?string $commandName): void
    {
        $command = $this->normalize($commandName);

        if ($command === '') {
            return;
        }

        $isDestructive = in_array($command, config('mtt_safety.destructive_commands', []), true);
        $isAllowed = (bool) config('mtt_safety.allow_destructive_db', false)
            || (app()->environment('testing') && (bool) config('mtt_safety.test_allow_destructive_db', false));

        if ($isDestructive && !$isAllowed) {
            throw new RuntimeException(
                "Blocked destructive database command: {$command}. This project forbids migrate:fresh / migrate:refresh / db:wipe by default. To allow (rare), set ALLOW_DESTRUCTIVE_DB=true temporarily."
            );
        }
    }

    private function normalize(?string $commandName): string
    {
        if (!$commandName) {
            return '';
        }

        return trim(strtolower($commandName));
    }
}
