<?php

namespace App\Console\Commands;

use App\Models\ArchiveSetting;
use App\Services\Archiving\ArchiveExecutor;
use Illuminate\Console\Command;

class RunArchive extends Command
{
    protected $signature = 'archive:run {--setting=* : Specific archive_setting IDs to run}';

    protected $description = 'Execute archive operations based on configured archive settings';

    public function handle(): int
    {
        $ids = collect($this->option('setting'))
            ->filter()
            ->map(fn ($v) => (int) $v)
            ->filter();

        $query = ArchiveSetting::query()
            ->where('enabled', true)
            // Manual strategies are never auto-run via the job
            ->where('strategy', '!=', 'manual');
        if ($ids->isNotEmpty()) {
            $query->whereIn('id', $ids);
        }

        $settings = $query->get();
        if ($settings->isEmpty()) {
            $this->info('No enabled archive settings found.');

            return self::SUCCESS;
        }

        $executor = app(ArchiveExecutor::class);
        $overall = [];
        foreach ($settings as $setting) {
            $this->line("Processing setting #{$setting->id} (".($setting->name ?? 'unnamed').')');
            $res = $executor->executeSetting($setting);
            foreach ($res as $table => $count) {
                $overall[$table] = ($overall[$table] ?? 0) + $count;
                $this->line("  - {$table}: {$count} affected");
            }
        }

        $this->info('Archive run complete.');
        if (empty($overall)) {
            $this->info('No rows matched any archive setting.');
        } else {
            $this->table(['Table', 'Affected'], collect($overall)->map(fn ($c, $t) => [$t, $c])->values()->all());
        }

        return self::SUCCESS;
    }
}
