<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Services\Runbooks\FindingsLifecycleBackfillRunbookService;
use App\Services\Runbooks\FindingsLifecycleBackfillScope;
use App\Services\Runbooks\RunbookReason;
use Illuminate\Console\Command;
use Illuminate\Validation\ValidationException;

class TenantpilotRunDeployRunbooks extends Command
{
    protected $signature = 'tenantpilot:run-deploy-runbooks';

    protected $description = 'Run deploy-time runbooks idempotently.';

    public function handle(FindingsLifecycleBackfillRunbookService $runbookService): int
    {
        try {
            $runbookService->start(
                scope: FindingsLifecycleBackfillScope::allTenants(),
                initiator: null,
                reason: new RunbookReason(
                    reasonCode: RunbookReason::CODE_DATA_REPAIR,
                    reasonText: 'Deploy hook automated runbooks',
                ),
                source: 'deploy_hook',
            );

            $this->info('Deploy runbooks started (if needed).');

            return self::SUCCESS;
        } catch (ValidationException $e) {
            $errors = $e->errors();

            $skippable = isset($errors['preflight.affected_count']) || isset($errors['scope']);

            if ($skippable) {
                $this->info('Deploy runbooks skipped (nothing to do or already running).');

                return self::SUCCESS;
            }

            $this->error('Deploy runbooks blocked by validation errors.');

            return self::FAILURE;
        }
    }
}
