<?php

namespace App\Models\Institution;

use App\Interface\AddressOwner;
use App\Interface\HistoryOwner;
use App\Interface\NoteOwner;
use App\Models\Claim\CareSetting;
use App\Models\Claim\Claim;
use App\Models\Dsar\DsarType;
use App\Trait\BelongsToSolicitor;
use App\Trait\HasAddresses;
use App\Trait\HasHistory;
use App\Trait\HasNotes;
use App\Trait\HasSlug;
use App\Trait\HasTags;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Institution extends Model implements AddressOwner, HistoryOwner, NoteOwner {

    public $fillable = [
        'solicitor_id',
        'slug',
        'display_name',
        'institution_type_id',
        'dsar_type_id',
        'send_type',
        'is_prioritised',
    ];

    protected $casts = [
        'is_prioritised' => 'boolean',
    ];

    use  BelongsToSolicitor, SoftDeletes, HasFactory, HasSlug, HasAddresses, HasHistory, HasNotes, HasTags;

    public function relatedInstitutions() {
        return $this->belongsToMany(
            Institution::class,
            'institution_relations',
            'institution_id',
            'related_institution_id'
        )->withTimestamps();
    }

    public function type() {
        return $this->belongsTo(InstitutionType::class, 'institution_type_id');
    }

    public function dsarType() {
        return $this->belongsTo(DsarType::class);
    }

    public function aliases() {
        return $this->hasMany(InstitutionAlias::class);
    }

    public function contacts() {
        return $this->hasMany(InstitutionContact::class)->orderBy('email')->orderBy('name');
    }

    public function careSettings() {
        return $this->hasMany(CareSetting::class);
    }

    public function claims() {
        return $this->belongsToMany(Claim::class, 'claim_institution')->withTimestamps();
    }

    public function hasAttachedClients(): bool {
        return $this->careSettings()->exists() || $this->claims()->exists();
    }

    protected function displayId(): Attribute {
        return Attribute::make(
            get: fn() => $this->id + 100,
        );
    }
}
