<?php

namespace App\Models;

use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Crypt;

class MessagingCredential extends Model
{
    use BelongsToOwner;

    public const STATUS_VALID = 'valid';

    public const STATUS_INVALID = 'invalid';

    protected $table = 'care_messaging_credentials';

    protected $fillable = [
        'owner_ref',
        'organization_id',
        'sms_api_key_encrypted',
        'sms_api_key_prefix',
        'sms_sender_id',
        'sms_status',
        'sms_validated_at',
        'sms_last_error',
        'bird_api_key_encrypted',
        'bird_api_key_prefix',
        'bird_from_email',
        'bird_from_name',
        'bird_status',
        'bird_validated_at',
        'bird_last_error',
    ];

    protected $hidden = [
        'sms_api_key_encrypted',
        'bird_api_key_encrypted',
    ];

    protected $casts = [
        'sms_validated_at' => 'datetime',
        'bird_validated_at' => 'datetime',
    ];

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

    public function hasValidSms(): bool
    {
        return $this->sms_status === self::STATUS_VALID
            && filled($this->sms_api_key_encrypted)
            && filled($this->sms_sender_id);
    }

    public function hasValidBird(): bool
    {
        return $this->bird_status === self::STATUS_VALID
            && filled($this->bird_api_key_encrypted)
            && filled($this->bird_from_email);
    }

    public function smsApiKey(): ?string
    {
        if (! filled($this->sms_api_key_encrypted)) {
            return null;
        }

        try {
            return Crypt::decryptString($this->sms_api_key_encrypted);
        } catch (\Throwable) {
            return null;
        }
    }

    public function birdApiKey(): ?string
    {
        if (! filled($this->bird_api_key_encrypted)) {
            return null;
        }

        try {
            return Crypt::decryptString($this->bird_api_key_encrypted);
        } catch (\Throwable) {
            return null;
        }
    }

    public static function encryptKey(string $plain): string
    {
        return Crypt::encryptString($plain);
    }
}
