<?php

declare(strict_types=1);

namespace App\Services\NovaCards;

use App\Models\NovaCard;
use App\Models\User;

class NovaCardLineageService
{
    public function __construct(
        private readonly NovaCardPresenter $presenter,
    ) {
    }

    public function resolve(NovaCard $card, ?User $viewer = null): array
    {
        $trailCards = [];
        $cursor = $card;
        $visited = [];

        while ($cursor && ! in_array($cursor->id, $visited, true)) {
            $visited[] = $cursor->id;
            $trailCards[] = $cursor;
            $cursor = $cursor->originalCard?->loadMissing(['user.profile', 'category', 'template', 'backgroundImage', 'tags', 'originalCard.user', 'rootCard.user']);
        }

        $trailCards = array_reverse($trailCards);
        $rootCard = $card->rootCard ?? ($trailCards[0] ?? $card);

        $family = NovaCard::query()
            ->with(['user.profile', 'category', 'template', 'backgroundImage', 'tags', 'originalCard', 'rootCard'])
            ->where(function ($query) use ($rootCard): void {
                $query->where('id', $rootCard->id)
                    ->orWhere('root_card_id', $rootCard->id)
                    ->orWhere('original_card_id', $rootCard->id);
            })
            ->published()
            ->orderByDesc('published_at')
            ->get();

        return [
            'card' => $this->presenter->card($card, false, $viewer),
            'trail' => $this->presenter->cards($trailCards, false, $viewer),
            'root_card' => $this->presenter->card($rootCard, false, $viewer),
            'family_cards' => $this->presenter->cards($family, false, $viewer),
        ];
    }
}