<?php

namespace App\Models;

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

class SupportMessage extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'assigned_agent_id',
        'subject',
        'message',
        'status',
        'priority',
        'category',
        'resolved_at',
        'first_response_at',
    ];

    protected $casts = [
        'resolved_at' => 'datetime',
        'first_response_at' => 'datetime',
    ];

    // Status constants
    const STATUS_OPEN = 'open';
    const STATUS_PENDING = 'pending';
    const STATUS_RESOLVED = 'resolved';
    const STATUS_CLOSED = 'closed';

    // Priority constants
    const PRIORITY_LOW = 'low';
    const PRIORITY_NORMAL = 'normal';
    const PRIORITY_HIGH = 'high';
    const PRIORITY_URGENT = 'urgent';

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

    public function assignedAgent()
    {
        return $this->belongsTo(User::class, 'assigned_agent_id');
    }

    public function replies()
    {
        return $this->hasMany(SupportReply::class)->orderBy('created_at', 'asc');
    }

    public function scopeOpen($query)
    {
        return $query->where('status', self::STATUS_OPEN);
    }

    public function scopePending($query)
    {
        return $query->where('status', self::STATUS_PENDING);
    }

    public function scopeResolved($query)
    {
        return $query->where('status', self::STATUS_RESOLVED);
    }

    public function scopeAssignedTo($query, $agentId)
    {
        return $query->where('assigned_agent_id', $agentId);
    }

    public function scopeUnassigned($query)
    {
        return $query->whereNull('assigned_agent_id');
    }

    public function isAssignedTo($agentId)
    {
        return $this->assigned_agent_id == $agentId;
    }

    public function markAsResolved($agentId = null)
    {
        $this->status = self::STATUS_RESOLVED;
        $this->resolved_at = now();
        if ($agentId) {
            $this->assigned_agent_id = $agentId;
        }
        $this->save();
    }

    public function assignToAgent($agentId)
    {
        $this->assigned_agent_id = $agentId;
        $this->status = self::STATUS_PENDING;
        $this->save();
    }
}
