<?php

namespace App\Models;

use App\Models\PensionCase\PensionCase;
use App\Trait\BelongsToSolicitor;
use App\Models\User\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Task extends Model
{
    public const UPDATE_CLIENT_TITLE = 'Update Client';

    protected $fillable = [
        'solicitor_id',
        'owner_type',
        'owner_id',
        'user_id',
        'title',
        'description',
        'due_at',
        'completed_at',
    ];

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

    use BelongsToSolicitor, SoftDeletes, HasFactory;

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

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

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

    public function ownerLabel(): ?string
    {
        if (!$this->owner) {
            return null;
        }

        if (method_exists($this->owner, 'display_name')) {
            return $this->owner->display_name;
        }

        if (isset($this->owner->nameFull)) {
            return $this->owner->nameFull;
        }

        if (isset($this->owner->display_name)) {
            return $this->owner->display_name;
        }

        if (isset($this->owner->name_first) && isset($this->owner->name_last)) {
            return $this->owner->name_first . ' ' . $this->owner->name_last;
        }

        if($this->owner instanceof PensionCase) {
            return $this->owner->client->name_first . ' ' . $this->owner->client->name_last;
        }

        return class_basename($this->owner);
    }

    public function ownerRoute(): ?string
    {
        if (!$this->owner) {
            return null;
        }

        if ($this->owner instanceof \App\Models\Client\Client) {
            return route('clients.show', $this->owner);
        }

        if($this->owner instanceof \App\Models\PensionCase\PensionCase) {
            return route('pension-cases.view', $this->owner);
        }

        return null;
    }
}
