<?php

namespace App\Models;

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

class MsgraphPendingChange extends Model
{
    use HasFactory;

    protected $fillable = [
        'model_type',
        'model_id',
        'action',
        'user_id',
        'old_membership_type',
        'new_membership_type',
        '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();
    }

    /**
     * Get the user that was affected by the change
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 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 for a specific model
     */
    public function scopeForModel($query, $model)
    {
        return $query->where('model_type', get_class($model))
                    ->where('model_id', $model->id);
    }

    /**
     * Scope for changes for a specific user
     */
    public function scopeForUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }

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

    /**
     * Get the user name for display purposes
     */
    public function getUserNameAttribute(): string
    {
        return $this->user ? ($this->user->name . ' ' . $this->user->last_name) : 'Unknown User';
    }

    /**
     * Mark this change as processed
     */
    public function markAsProcessed(): bool
    {
        $this->processed = true;
        $this->processed_at = now();
        return $this->save();
    }

    /**
     * Mark this change as failed
     */
    public function markAsFailed(string $errorMessage = null): bool
    {
        // You could add an error_message field to store the error
        // For now, we'll just keep it unprocessed
        if ($errorMessage) {
            $metadata = $this->metadata ?? [];
            $metadata['error_message'] = $errorMessage;
            $metadata['failed_at'] = now()->toISOString();
            $this->metadata = $metadata;
            return $this->save();
        }
        return false;
    }
}
