<?php

namespace App\Console\Commands;

use App\Master\Models\Seed;
use App\Traits\TrackedSeeding;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File;

class SeedGlobalData extends Command
{
    use TrackedSeeding;

    private $batch = 0;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'seed:global  {--retry}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Seed global data';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if ($this->option('retry')) {
            $this->retryLast();
        } else {
            $this->runSeed();
        }
        return Command::SUCCESS;
    }

    private function runSeed(): void
    {
        $seeds = $this->getSeeders();

        $this->batch = Seed::query()->max('batch') ?? 0;
        $this->batch++;
        $seeds->each(fn ($seeder) => $this->trackedSeed($seeder));
    }

    private function retryLast()
    {
        $this->batch = Seed::query()->max('batch') ?? 0;

        Seed::query()
            ->where('batch', $this->batch)
            ->get()
            ->each(fn ($seeder) => $this->trackedSeed($seeder->seeder, true, true));
    }

    public function getSeeders(): Collection
    {
        if (File::exists(base_path('vendor/composer/autoload_classmap.php')) === false) {
            throw new \Exception('No classmap to determine seeders');
        }

        return collect(require(base_path('vendor/composer/autoload_classmap.php')))
            ->filter(fn ($path, $class) => str_starts_with((string) $class, 'Database\\Seeders\\Global\\'))
            ->keys();
    }
}
