<?php

namespace App\Models;

use App\Models\Client\Client;
use App\Models\PensionCase\PensionCase;
use App\Models\User\User;
use App\Models\WillsCase\WillsCase;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

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

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

    use SoftDeletes;

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

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

    public function ownerLabel(): ?string {
        $owner = $this->owner;

        return match (true) {
            $owner instanceof Client      => trim(($owner->name_first ?? '') . ' ' . ($owner->name_last ?? '')) ?: $owner->displayId,
            $owner instanceof PensionCase => 'CPF ' . ($owner->case_number ?? $owner->displayId),
            $owner instanceof WillsCase   => 'W&T ' . ($owner->case_number ?? $owner->displayId),
            $owner !== null               => class_basename($owner) . ' #' . $owner->getKey(),
            default                       => null,
        };
    }

    public function ownerRoute(): ?string {
        $owner = $this->owner;

        return match (true) {
            $owner instanceof Client      => route('clients.show', $owner),
            $owner instanceof PensionCase => route('pension-cases.view', $owner),
            $owner instanceof WillsCase   => route('wills-cases.view', $owner),
            default                       => null,
        };
    }

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