<?php

declare(strict_types=1);

namespace Builder\Core\Foundation\Commands;

use Builder\Core\Foundation\Registry;
use Builder\Core\Foundation\Resources\Resource;
use Builder\Core\Foundation\Revisions\RevisionService;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

final class PruneRevisionsCommand extends Command
{
    protected $signature = 'builder:prune-revisions
                            {--resource= : Limit pruning to a single resource slug}';

    protected $description = 'Prune old revisions beyond the retention limit for each resource';

    public function __construct(
        private readonly Registry $registry,
        private readonly RevisionService $revisionService,
    ) {
        parent::__construct();
    }

    public function handle(): int
    {
        $resourceSlug = $this->option('resource');

        $resources = collect($this->registry->resources())
            ->map(fn (string $class): Resource => new $class)
            ->filter(fn (Resource $resource): bool => $resource->isRevisable())
            ->when(
                $resourceSlug !== null,
                fn (Collection $col): Collection => $col->filter(fn (Resource $r): bool => $r::getSlug() === $resourceSlug),
            )
            ->values();

        if ($resources->isEmpty()) {
            $this->info('No revisable resources found.');

            return self::SUCCESS;
        }

        $totalDeleted = 0;

        foreach ($resources as $resource) {
            $modelClass = $resource::getModel();
            $maxRevisions = $resource->getMaxRevisions();

            $deleted = $this->revisionService->pruneModelClass($modelClass, $maxRevisions);
            $totalDeleted += $deleted;

            if ($deleted > 0) {
                $this->line("  <fg=yellow>{$resource::getSlug()}</>: pruned {$deleted} revision(s).");
            }
        }

        $this->info("Done. Pruned {$totalDeleted} revision(s) in total.");

        return self::SUCCESS;
    }
}
