<?php

declare(strict_types=1);

namespace ImovelZapAi\Conversations\Infrastructure\Persistence\Eloquent;

use Database\Factories\TenantMessagingConfigFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use ImovelZapAi\Conversations\Domain\Enums\MessagingConnectionStatus;
use ImovelZapAi\Conversations\Domain\Enums\MessagingProvider;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\BelongsToTenant;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\HasUuidPrimaryKey;
use ImovelZapAi\Tenancy\Infrastructure\Persistence\Eloquent\TenantModel;

class TenantMessagingConfigModel extends Model
{
    use BelongsToTenant;

    /** @use HasFactory<TenantMessagingConfigFactory> */
    use HasFactory;
    use HasUuidPrimaryKey;

    protected $table = 'tenant_messaging_configs';

    /** @var list<string> */
    protected $fillable = [
        'tenant_id',
        'provider',
        'instance_name',
        'instance_token',
        'phone_number_id',
        'business_account_id',
        'access_token',
        'verify_token',
        'connection_status',
        'is_active',
        'automation_enabled',
    ];

    /** @return array<string, string> */
    protected function casts(): array
    {
        return [
            'provider' => MessagingProvider::class,
            'connection_status' => MessagingConnectionStatus::class,
            'access_token' => 'encrypted',
            'instance_token' => 'encrypted',
            'is_active' => 'boolean',
            'automation_enabled' => 'boolean',
        ];
    }

    public function automationEnabled(): bool
    {
        return (bool) ($this->automation_enabled ?? true);
    }

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(TenantModel::class, 'tenant_id');
    }

    public function isConnected(): bool
    {
        return $this->connection_status === MessagingConnectionStatus::Connected;
    }

    protected static function newFactory(): TenantMessagingConfigFactory
    {
        return TenantMessagingConfigFactory::new();
    }
}
