<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Mortezaa97\Reviews\Models\Review;

class Post extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $guarded = [
        'id',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'gallery' => 'array',
        'is_featured' => 'boolean',
        'publish_at' => 'datetime',
    ];

    protected $appends = [];

    protected $with = [];

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('order', function (Builder $builder): void {
            $builder->orderByDesc('created_at');
        });
    }

    public function getViewCountAttribute(): int
    {
        return (int) ($this->attributes['views'] ?? 0);
    }

    public function scopePublished(Builder $query): Builder
    {
        return $query->where('status', 13);
    }

    public function scopeForApi(Builder $query): Builder
    {
        return $query->with(['author', 'categories', 'tags']);
    }

    /*
    * Relations
    */
    public function createdBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updatedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'author_id');
    }

    public function bookmarks(): MorphMany
    {
        return $this->morphMany(Bookmark::class, 'bookmarkable');
    }

    public function reviews(): MorphMany
    {
        return $this->morphMany(Review::class, 'reviewable');
    }

    public function categories(): BelongsToMany
    {
        return $this->belongsToMany(
            related: Category::class,
            table: 'model_has_categories',
            foreignPivotKey: 'model_id',
            relatedPivotKey: 'category_id'
        );
    }

    public function tags(): BelongsToMany
    {
        return $this->morphToMany(related: Tag::class, name: 'model', table: 'model_has_tags', foreignPivotKey: 'model_id', relatedPivotKey: 'tag_id');
    }
}
