<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Route;

class NovaCardCollection extends Model
{
    public const VISIBILITY_PRIVATE = 'private';
    public const VISIBILITY_PUBLIC = 'public';

    protected $fillable = [
        'user_id',
        'slug',
        'name',
        'description',
        'visibility',
        'official',
        'featured',
        'cards_count',
    ];

    protected $casts = [
        'official' => 'boolean',
        'featured' => 'boolean',
        'cards_count' => 'integer',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function items(): HasMany
    {
        return $this->hasMany(NovaCardCollectionItem::class, 'collection_id');
    }

    public function cards(): BelongsToMany
    {
        return $this->belongsToMany(NovaCard::class, 'nova_card_collection_items', 'collection_id', 'card_id')
            ->withPivot(['note', 'sort_order'])
            ->withTimestamps();
    }

    public function isPubliclyVisible(): bool
    {
        return $this->official || $this->visibility === self::VISIBILITY_PUBLIC;
    }

    public function publicUrl(): ?string
    {
        if (! $this->exists || ! Route::has('cards.collections.show')) {
            return null;
        }

        return route('cards.collections.show', [
            'slug' => $this->slug,
            'id' => $this->id,
        ]);
    }
}