<?php

namespace App\Models\Solicitor;

use App\Casts\EmailAddress;
use App\Casts\PhoneNumber;
use App\Interface\AddressOwner;
use App\Interface\DocumentOwner;
use App\Interface\HistoryOwner;
use App\Interface\NoteOwner;
use App\Models\User\User;
use App\Trait\HasAddresses;
use App\Trait\HasDocuments;
use App\Trait\HasHistory;
use App\Trait\HasNotes;
use Illuminate\Database\Eloquent\Model;

class Solicitor extends Model implements AddressOwner, DocumentOwner, NoteOwner, HistoryOwner {
    protected $fillable = [
        'name',
        'domain',
        'email_address',
        'phone_number',
        'logo_path',
        'company_number',
        'sra_number',
    ];

    protected $casts = [
        'email_address' => EmailAddress::class,
        'phone_number' => PhoneNumber::class,
    ];

    use HasAddresses, HasNotes, HasDocuments, HasHistory;


    public function users() {
        return $this->hasMany(User::class);
    }

    public function emailSenders() {
        return $this->hasMany(SolicitorEmailSender::class);
    }

    /**
     * Return the preferred sending address for a given purpose (e.g. 'dsar', 'client').
     * Prefers an explicit default for that purpose, then any sender for that purpose,
     * then falls back to the general default, then any sender at all.
     */
    public function emailSenderFor(string $purpose): ?SolicitorEmailSender {
        return $this->emailSenders()->where('purpose', $purpose)->orderByDesc('is_default')->first()
            ?? $this->emailSenders()->where('purpose', 'general')->orderByDesc('is_default')->first()
            ?? $this->emailSenders()->orderByDesc('is_default')->first();
    }

    public function getDocumentStoragePath(): string {
        return "solicitors/" . $this->id . "/";
    }
}
