<?php

namespace App\Models\WillsCase;

use App\Interface\DocumentOwner;
use App\Interface\HistoryOwner;
use App\Interface\NoteOwner;
use App\Models\Client\Client;
use App\Trait\HasDocuments;
use App\Trait\HasHistory;
use App\Trait\HasNotes;
use App\Trait\HasSlug;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class WillsCase extends Model implements DocumentOwner, NoteOwner, HistoryOwner {
    use HasSlug, HasNotes, HasDocuments, HasHistory;

    protected $table = 'wills_cases';

    protected $fillable = [
        'client_id',
        'case_number',
        'opened_at',
        'closed_at',
        'is_open',
        'is_closed',
        'ifa_referred_date',
        'national_insurance',
        'ifa_referred',
        'fee_structure',
        'occupation',
        'created_by',
    ];

    protected $casts = [
        'is_open'          => 'boolean',
        'is_closed'        => 'boolean',
        'ifa_referred'     => 'boolean',
        'opened_at'        => 'datetime',
        'closed_at'        => 'datetime',
        'ifa_referred_date' => 'date',
    ];

    // -----------------------------------------------------------------------
    // Relationships
    // -----------------------------------------------------------------------

    public function client(): BelongsTo {
        return $this->belongsTo(Client::class);
    }

    public function comments(): HasMany {
        return $this->hasMany(WillsCaseComment::class)->orderByDesc('comment_created_at');
    }

    // -----------------------------------------------------------------------
    // Query scopes
    // -----------------------------------------------------------------------

    public function scopeOpen($query) {
        return $query->where('is_open', true);
    }

    public function scopeClosed($query) {
        return $query->where('is_closed', true);
    }

    // -----------------------------------------------------------------------
    // Computed attributes
    // -----------------------------------------------------------------------

    protected function displayId(): Attribute {
        return Attribute::make(
            get: fn() => 'WT' . str_pad($this->id, 5, '0', STR_PAD_LEFT),
        );
    }

    // -----------------------------------------------------------------------
    // DocumentOwner contract
    // -----------------------------------------------------------------------

    public function getDocumentStoragePath(): string {
        return 'clients/' . $this->client->slug . '/wills-cases/' . $this->id . '/';
    }
}
