<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Tag extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'id',
        'type',
        'name',
        'slug',
        'description',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'type' => 'integer',
    ];

    // Many-to-many relationship with articles
    public function articles(): BelongsToMany
    {
        return $this->belongsToMany(Article::class, 'article_tags')
            ->withTimestamps()
            ->wherePivotNull('deleted_at');
    }

    // Many-to-many relationship with published articles
    public function publishedArticles(): BelongsToMany
    {
        return $this->belongsToMany(Article::class, 'article_tags')
            ->withTimestamps()
            ->wherePivotNull('deleted_at')
            ->where('status', 'publish');
    }

    // Check if tag can be deleted (no articles associated)
    public function canDelete(): bool
    {
        return $this->articles()->count() === 0;
    }

    // Override delete to handle soft delete of related data
    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($tag) {
            if (! $tag->canDelete()) {
                throw new \Exception('Cannot delete tag that has associated articles');
            }
        });
    }
}
