<?php

namespace App\Console\Commands;

use App\DataFixes\BaseDataFix;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;

class FixDataCommand extends Command
{
    protected $signature = 'app:fix-data {--only=} {--skip=}';

    protected $description = 'Fix data yang bermasalah (cost, jumlah, dll)';

    public function handle(): int
    {
        $filesystem = new Filesystem;
        $fixPath = app_path('DataFixes');

        require_once $fixPath.'/BaseDataFix.php';

        $files = collect($filesystem->glob($fixPath.'/*.php'))
            ->map(fn ($file) => basename($file))
            ->filter(fn ($file) => $file !== 'BaseDataFix.php')
            ->toArray();

        $fixes = [];

        foreach ($files as $file) {
            require_once $fixPath.'/'.$file;

            $className = 'App\\DataFixes\\'.str_replace('.php', '', $file);

            if (! class_exists($className)) {
                continue;
            }

            $instance = new $className;

            if ($instance instanceof BaseDataFix) {
                $fixes[$instance->key()] = $instance;
            }
        }

        $only = $this->option('only') ? explode(',', $this->option('only')) : null;
        $skip = $this->option('skip') ? explode(',', $this->option('skip')) : [];

        $this->newLine();
        $this->info('=== Fix Data ===');
        $this->newLine();

        $summary = [];
        $totalFixed = 0;
        $totalSkipped = 0;

        foreach ($fixes as $key => $fix) {
            if ($only !== null && ! in_array($key, $only)) {
                continue;
            }

            if (in_array($key, $skip)) {
                $this->line("SKIP  {$key} — {$fix->description()}");

                continue;
            }

            $fix->setCommand($this);
            $this->info("Running: {$fix->description()}");

            $result = $fix->fix();

            $fixed = $result['fixed'] ?? 0;
            $skipped = $result['skipped'] ?? 0;
            $total = $result['total'] ?? 0;

            $summary[$key] = [
                'Fix' => $key,
                'Total' => $total,
                'Fixed' => $fixed,
                'Skipped' => $skipped,
            ];

            $totalFixed += $fixed;
            $totalSkipped += $skipped;

            $this->line("  OK    Fixed: {$fixed}, Skipped: {$skipped}, Total: {$total}");
            $this->newLine();
        }

        $this->info('=== Summary ===');
        $this->info("Total fixed: {$totalFixed}");
        $this->info("Total skipped: {$totalSkipped}");
        $this->newLine();

        if (! empty($summary)) {
            $this->table(
                ['Fix', 'Total', 'Fixed', 'Skipped'],
                array_values($summary)
            );
        }

        return Command::SUCCESS;
    }
}
