<?php

namespace App\Models\Communication;

use App\Models\Solicitor\Solicitor;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class SolicitorPhoneNumber extends Model {
    public $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',
    ];

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

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

    public function type(): BelongsTo {
        return $this->belongsTo(PhoneNumberType::class, 'phone_number_type_id');
    }

    public function calls(): HasMany {
        return $this->hasMany(Call::class, 'solicitor_phone_number_id');
    }

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

    public function scopePrimary(Builder $query): Builder {
        return $query->where('is_primary', true);
    }

    public function scopeForSolicitor(Builder $query, int $solicitorId): Builder {
        return $query->where('solicitor_id', $solicitorId);
    }

    public function scopeOfType(Builder $query, string $slug): Builder {
        return $query->whereHas('type', function (Builder $query) use ($slug)
        {
            $query->where('slug', $slug);
        });
    }

    /*
    |--------------------------------------------------------------------------
    | Helpers
    |--------------------------------------------------------------------------
    */

    public function isVoiceEnabled(): bool {
        return $this->supportsChannel('voice');
    }

    public function supportsChannel(string $channel): bool {
        $capabilities = $this->capabilities ?? [];

        return in_array($channel, $capabilities, true);
    }

    public function isSmsEnabled(): bool {
        return $this->supportsChannel('sms');
    }

    public function isWhatsappEnabled(): bool {
        return $this->supportsChannel('whatsapp');
    }

    public function getDisplayLabelAttribute(): string {
        $label = $this->label ?: ($this->type?->name ?? 'Phone Number');

        return "{$label} ({$this->phone_number})";
    }

    public function getRouteKeyLabelAttribute(): string {
        return $this->label
            ?: $this->normalized_phone_number
                ?: $this->phone_number
                    ?: 'Phone Number #' . $this->getKey();
    }
}
