<?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',
        'area_id',
        'dsar_type_id',
        'send_type',
        'is_prioritised',
        'stated_sar_backlog',
        'sar_backlog_updated_at',
    ];

    protected $casts = [
        'is_prioritised'         => 'boolean',
        'stated_sar_backlog'     => 'integer',
        'sar_backlog_updated_at' => 'datetime',
    ];

    use 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 area() {
        return $this->belongsTo(\App\Models\Claim\Area::class);
    }

    /** The institution's area name, or null. */
    public function areaName(): ?string
    {
        return $this->area?->name;
    }

    /** The institution's local authority (its area's council) name, or null. */
    public function localAuthority(): ?string
    {
        return $this->area?->council?->name;
    }

    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 dsars() {
        return $this->hasMany(\App\Models\Dsar\Dsar::class);
    }

    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,
        );
    }
}
