<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Illuminate\Support\Facades\Schema;

class QueueListCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'queue:list {--queue= : Szűrés a queue nevére} {--failed : A hibás jobok kilistázása}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Kilistázza a várólistán lévő (vagy hibás) jobokat táblázatos formában';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $queueFilter = $this->option('queue');
        $showFailed = $this->option('failed');

        $tableName = $showFailed ? 'failed_jobs' : 'jobs';

        if (!Schema::hasTable($tableName)) {
            $this->error("A(z) {$tableName} tábla nem létezik.");
            return 1;
        }

        $query = DB::table($tableName);

        if ($queueFilter) {
            $query->where('queue', $queueFilter);
        }

        $jobs = $query->orderBy($showFailed ? 'failed_at' : 'created_at', 'desc')->get();

        if ($jobs->isEmpty()) {
            $this->info("Nincsenek " . ($showFailed ? "hibás " : "") . "jobok a várólistán.");
            return 0;
        }

        $tableData = $jobs->map(function ($job) use ($showFailed) {
            $payload = json_decode($job->payload, true);
            $displayName = $payload['displayName'] ?? 'Ismeretlen';

            if ($showFailed) {
                return [
                    'ID' => $job->id,
                    'Queue' => $job->queue,
                    'Job Class' => $displayName,
                    'Failed At' => $job->failed_at,
                    'Exception' => substr($job->exception, 0, 70) . '...',
                ];
            }

            return [
                'ID' => $job->id,
                'Queue' => $job->queue,
                'Job Class' => $displayName,
                'Attempts' => $job->attempts,
                'Reserved At' => $job->reserved_at ? Carbon::createFromTimestamp($job->reserved_at)->format('Y.m.d H:i:s') : 'Nincs lefoglalva',
                'Available At' => Carbon::createFromTimestamp($job->available_at)->format('Y.m.d H:i:s'),
                'Created At' => Carbon::createFromTimestamp($job->created_at)->format('Y.m.d H:i:s'),
            ];
        });

        if ($showFailed) {
            $headers = ['ID', 'Queue', 'Job Class', 'Failed At', 'Exception'];
        } else {
            $headers = ['ID', 'Queue', 'Job Class', 'Próbálkozások', 'Lefoglalva', 'Elérhető', 'Létrehozva'];
        }

        $this->table($headers, $tableData);

        return 0;
    }
}
