<?php

declare(strict_types=1);

namespace App\Framework\WebPush\ValueObjects;

/**
 * Push Notification Send Result.
 *
 * Ergebnis eines Web Push Notification Versands.
 */
final readonly class SendResult
{
    public function __construct(
        public bool $success,
        public int $statusCode,
        public ?string $errorMessage = null,
        public bool $subscriptionExpired = false
    ) {
    }

    /**
     * Erstellt erfolgreiches Ergebnis.
     */
    public static function success(int $statusCode = 201): self
    {
        return new self(
            success: true,
            statusCode: $statusCode
        );
    }

    /**
     * Erstellt fehlgeschlagenes Ergebnis.
     */
    public static function failure(int $statusCode, string $errorMessage): self
    {
        return new self(
            success: false,
            statusCode: $statusCode,
            errorMessage: $errorMessage
        );
    }

    /**
     * Erstellt Ergebnis für abgelaufene Subscription.
     */
    public static function subscriptionExpired(int $statusCode = 410): self
    {
        return new self(
            success: false,
            statusCode: $statusCode,
            errorMessage: 'Subscription expired or invalid',
            subscriptionExpired: true
        );
    }

    /**
     * Prüft ob Subscription gelöscht werden sollte.
     */
    public function shouldDeleteSubscription(): bool
    {
        // 404 = Not Found, 410 = Gone
        return $this->subscriptionExpired
            || in_array($this->statusCode, [404, 410], true);
    }

    /**
     * Konvertiert zu Array.
     *
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'success' => $this->success,
            'status_code' => $this->statusCode,
            'error_message' => $this->errorMessage,
            'subscription_expired' => $this->subscriptionExpired,
            'should_delete_subscription' => $this->shouldDeleteSubscription(),
        ];
    }
}
