<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class MsgraphModelChange extends Model
{
    use HasFactory;

    protected $fillable = [
        'model_type',
        'model_id',
        'action',
        'old_status',
        'new_status',
        'old_title',
        'new_title',
        'language',
        'metadata',
        'processed',
        'processed_at',
        'priority'
    ];

    protected $casts = [
        'metadata' => 'array',
        'processed' => 'boolean',
        'processed_at' => 'datetime',
    ];

    /**
     * Get the model that the change belongs to (Committee or WorkGroup)
     */
    public function model(): MorphTo
    {
        return $this->morphTo();
    }

    /**
     * Scope for unprocessed changes
     */
    public function scopeUnprocessed($query)
    {
        return $query->where('processed', false);
    }

    /**
     * Scope for processed changes
     */
    public function scopeProcessed($query)
    {
        return $query->where('processed', true);
    }

    /**
     * Scope for changes by priority
     */
    public function scopeByPriority($query, string $priority)
    {
        return $query->where('priority', $priority);
    }

    /**
     * Scope for changes by action
     */
    public function scopeByAction($query, string $action)
    {
        return $query->where('action', $action);
    }

    /**
     * Scope for changes for a specific model
     */
    public function scopeForModel($query, $model)
    {
        return $query->where('model_type', get_class($model))
                    ->where('model_id', $model->id);
    }

    /**
     * Get the model title for display purposes
     */
    public function getModelTitleAttribute(): string
    {
        if ($this->new_title) {
            return $this->new_title;
        }

        if ($this->old_title) {
            return $this->old_title;
        }

        return $this->model->title ?? 'Unknown';
    }
}
