<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SmsProfile extends Model
{
    use HasFactory;

    protected $table = 'sms_profiles';

    protected $fillable = [
        'uuid',
        'name',
        'active',
        'api_username',
        'default_sender_id',
        'settings',
    ];

    protected $casts = [
        'active' => 'boolean',
        'settings' => 'array',
    ];

    protected $hidden = [
        'encrypted_api_password',
    ];

    // Write-only password setter
    public function setApiPasswordAttribute(string $plain): void
    {
        $this->attributes['encrypted_api_password'] = app(\App\Services\MailSecretEncrypter::class)->encrypt($plain);
    }

    public function decryptApiPassword(): ?string
    {
        if (! isset($this->attributes['encrypted_api_password'])) {
            return null;
        }

        return app(\App\Services\MailSecretEncrypter::class)->decrypt($this->attributes['encrypted_api_password']);
    }

    public function senders()
    {
        return $this->hasMany(SmsSender::class, 'profile_id');
    }

    public function logs()
    {
        return $this->hasMany(SmsLog::class, 'profile_id');
    }
}
