<?php

namespace App\Filament\Resources\PolicyVersionResource\Pages;

use App\Filament\Resources\PolicyVersionResource;
use App\Support\Navigation\CrossResourceNavigationMatrix;
use App\Support\Navigation\RelatedContextEntry;
use App\Support\Navigation\RelatedNavigationResolver;
use Filament\Actions\Action;
use Filament\Resources\Pages\ViewRecord;
use Filament\Support\Enums\Width;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Model;

class ViewPolicyVersion extends ViewRecord
{
    protected static string $resource = PolicyVersionResource::class;

    protected Width|string|null $maxContentWidth = Width::Full;

    protected function resolveRecord(int|string $key): Model
    {
        return PolicyVersionResource::resolveScopedRecordOrFail($key);
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('primary_related')
                ->label(fn (): string => $this->primaryRelatedEntry()?->actionLabel ?? 'Open related record')
                ->url(fn (): ?string => $this->primaryRelatedEntry()?->targetUrl)
                ->hidden(fn (): bool => ! ($this->primaryRelatedEntry()?->isAvailable() ?? false))
                ->color('gray'),
        ];
    }

    public function getFooter(): ?View
    {
        return view('filament.resources.policy-version-resource.pages.view-policy-version-footer', [
            'record' => $this->getRecord(),
        ]);
    }

    private function primaryRelatedEntry(bool $fresh = false): ?RelatedContextEntry
    {
        $resolver = app(RelatedNavigationResolver::class);

        return $fresh
            ? $resolver->primaryListActionFresh(CrossResourceNavigationMatrix::SOURCE_POLICY_VERSION, $this->getRecord())
            : $resolver->primaryListAction(CrossResourceNavigationMatrix::SOURCE_POLICY_VERSION, $this->getRecord());
    }
}
