<?php

declare(strict_types=1);

namespace App\Application\LiveComponents\Dashboard;

use App\Application\LiveComponents\LiveComponentState;

/**
 * Type-safe state for FailedJobsListComponent
 *
 * Provides real-time failed jobs monitoring and management.
 * Displays dead letter queue jobs with retry functionality.
 */
final readonly class FailedJobsState implements LiveComponentState
{
    public function __construct(
        public int $totalFailedJobs = 0,
        public array $failedJobs = [], // [['id' => string, 'queue' => string, 'error' => string, 'failed_at' => string, 'attempts' => int]]
        public array $statistics = [], // ['by_queue' => [...], 'by_error_type' => [...]]
        public string $lastUpdated = ''
    ) {}

    /**
     * Create from array data (from client or storage)
     */
    public static function fromArray(array $data): self
    {
        return new self(
            totalFailedJobs: (int) ($data['totalFailedJobs'] ?? $data['total_failed_jobs'] ?? 0),
            failedJobs: (array) ($data['failedJobs'] ?? $data['failed_jobs'] ?? []),
            statistics: (array) ($data['statistics'] ?? []),
            lastUpdated: (string) ($data['lastUpdated'] ?? $data['last_updated'] ?? '')
        );
    }

    /**
     * Create empty state with defaults
     */
    public static function empty(): self
    {
        return new self();
    }

    /**
     * Update with fresh failed jobs data
     */
    public function withFailedJobs(
        int $totalFailedJobs,
        array $failedJobs,
        array $statistics
    ): self {
        return new self(
            totalFailedJobs: $totalFailedJobs,
            failedJobs: $failedJobs,
            statistics: $statistics,
            lastUpdated: date('H:i:s')
        );
    }

    /**
     * Update timestamp
     */
    public function withLastUpdated(string $timestamp): self
    {
        return new self(
            totalFailedJobs: $this->totalFailedJobs,
            failedJobs: $this->failedJobs,
            statistics: $this->statistics,
            lastUpdated: $timestamp
        );
    }

    /**
     * Convert to array for template rendering
     */
    public function toArray(): array
    {
        return [
            'totalFailedJobs' => $this->totalFailedJobs,
            'failedJobs' => $this->failedJobs,
            'statistics' => $this->statistics,
            'lastUpdated' => $this->lastUpdated,
        ];
    }
}
