<?php

declare(strict_types=1);

namespace App\Application\LiveComponents\ValueObjects;

/**
 * Activity - Represents a single activity in the feed
 */
final readonly class Activity
{
    public function __construct(
        public string $id,
        public ActivityType $type,
        public string $userId,
        public string $userName,
        public string $content,
        public int $timestamp,
        public bool $isRead = false,
        public ?string $avatarUrl = null,
        public array $metadata = []
    ) {
    }

    public function markAsRead(): self
    {
        return new self(
            id: $this->id,
            type: $this->type,
            userId: $this->userId,
            userName: $this->userName,
            content: $this->content,
            timestamp: $this->timestamp,
            isRead: true,
            avatarUrl: $this->avatarUrl,
            metadata: $this->metadata
        );
    }

    public function getRelativeTime(): string
    {
        $diff = time() - $this->timestamp;

        if ($diff < 60) {
            return 'gerade eben';
        }

        if ($diff < 3600) {
            $minutes = floor($diff / 60);

            return $minutes === 1 ? 'vor 1 Minute' : "vor {$minutes} Minuten";
        }

        if ($diff < 86400) {
            $hours = floor($diff / 3600);

            return $hours === 1 ? 'vor 1 Stunde' : "vor {$hours} Stunden";
        }

        $days = floor($diff / 86400);

        return $days === 1 ? 'vor 1 Tag' : "vor {$days} Tagen";
    }

    public function getAbsoluteTime(): string
    {
        return date('d.m.Y H:i:s', $this->timestamp);
    }

    public function getDateGroup(): ActivityDateGroup
    {
        $now = time();
        $todayStart = strtotime('today', $now);
        $yesterdayStart = strtotime('yesterday', $now);
        $weekStart = strtotime('last monday', $now);

        if ($this->timestamp >= $todayStart) {
            return ActivityDateGroup::TODAY;
        }

        if ($this->timestamp >= $yesterdayStart) {
            return ActivityDateGroup::YESTERDAY;
        }

        if ($this->timestamp >= $weekStart) {
            return ActivityDateGroup::THIS_WEEK;
        }

        return ActivityDateGroup::OLDER;
    }

    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'type' => $this->type->value,
            'user_id' => $this->userId,
            'user_name' => $this->userName,
            'avatar_url' => $this->avatarUrl,
            'content' => $this->content,
            'metadata' => $this->metadata,
            'timestamp' => $this->timestamp,
            'is_read' => $this->isRead,
        ];
    }
}
