<?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;
use Illuminate\Support\Facades\Storage;

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',
        'twilio_twiml_app_sid',
        'is_active',
        'is_primary',
        'capabilities',
        'voicemail_greeting_path',
    ];

    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 hasVoicemailGreeting(): bool {
        return filled($this->voicemail_greeting_path)
            && Storage::exists($this->voicemail_greeting_path);
    }

    /**
     * Absolute, publicly reachable URL to this line's voicemail greeting MP3,
     * suitable for Twilio's <Play> verb. Returns null when no greeting is set,
     * in which case callers fall back to a spoken <Say> prompt.
     */
    public function voicemailGreetingUrl(): ?string {
        if (! $this->hasVoicemailGreeting()) {
            return null;
        }

        return url(Storage::url($this->voicemail_greeting_path));
    }

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