<?php

namespace App\Models;

use App\Trait\BelongsToSolicitor;
use App\Models\Contact\Hub\ContactMessage;
use App\Models\User\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Task extends Model
{
    protected $fillable = [
        'user_id',
        'assigned_by',
        'contact_message_id',
        'title',
        'description',
        'due_at',
        'completed_at',
    ];

    protected $casts = [
        'due_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    use BelongsToSolicitor, SoftDeletes;

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

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

    public function owner() {
        return $this->morphTo();
    }

    public function message() {
        return $this->belongsTo(ContactMessage::class, 'contact_message_id');
    }

    protected static function boot() {
        parent::boot();
        static::addGlobalScope('outstanding', function (Builder $builder) {
            $builder->whereNull('completed_at');
        });
    }
}
