<?php

namespace App\Models\Solicitor;

use App\Contracts\Communications\CommunicationSender;
use App\Enum\Contact\MessageChannel;
use App\Trait\BelongsToSolicitor;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class SolicitorPhoneNumber extends Model implements CommunicationSender
{
    use BelongsToSolicitor;

    protected $table = 'solicitor_phone_numbers';

    protected $fillable = [
        'solicitor_id',
        'phone_number_type_id',
        'label',
        'phone_number',
        'normalized_phone_number',
        'provider',
        'twilio_account_sid',
        'twilio_subaccount_sid',
        'twilio_phone_number_sid',
        'is_active',
        'is_primary',
        'capabilities',
        'meta',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'is_primary' => 'boolean',
        'capabilities' => 'array',
        'meta' => 'array',
    ];

    public function scopeActive(Builder $q): Builder
    {
        return $q->where('is_active', true);
    }

    public function scopeSmsCapable(Builder $q): Builder
    {
        return $q->whereJsonContains('capabilities', 'sms');
    }

    public function supportsSms(): bool
    {
        return in_array('sms', $this->capabilities ?? [], true);
    }

    // --- CommunicationSender contract ---

    public function id(): int
    {
        return (int) $this->attributes['id'];
    }

    public function label(): string
    {
        return trim(($this->label ?: $this->phone_number) . ' (' . $this->phone_number . ')');
    }

    public function value(): string
    {
        return (string) ($this->normalized_phone_number ?? $this->phone_number);
    }

    public function channel(): MessageChannel
    {
        return MessageChannel::SMS;
    }

    public function replyTo(): ?string
    {
        return null;
    }

    public function signatureHtml(): ?string
    {
        return null;
    }

    public function signatureText(): ?string
    {
        return null;
    }

    public function providerConfig(): array
    {
        return [
            'provider' => $this->provider,
            'twilio_account_sid' => $this->twilio_account_sid,
            'twilio_subaccount_sid' => $this->twilio_subaccount_sid,
            'twilio_phone_number_sid' => $this->twilio_phone_number_sid,
            'capabilities' => $this->capabilities ?? [],
        ];
    }
}
