<?php

namespace App\Models;

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

class MailProfile extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'active', 'auto_mailer', 'host', 'port', 'encryption', 'username', 'from_address', 'from_name',
        'reply_to_address', 'reply_to_name', 'priority', 'signature', 'max_daily_quota', 'emails_sent_today',
        'last_success_at', 'last_error_at', 'last_error_message', 'failover_to_id', 'test_status', 'test_checked_at',
    ];

    protected $casts = [
        'active' => 'boolean',
        'auto_mailer' => 'boolean',
        'signature' => 'array',
        'last_success_at' => 'datetime',
        'last_error_at' => 'datetime',
        'test_checked_at' => 'datetime',
    ];

    protected $hidden = [
        'encrypted_password',
    ];

    protected static function booted(): void
    {
        static::created(function (MailProfile $profile): void {

            \Log::info('mail_profile.created', [
                'id' => $profile->id,
                'name' => $profile->name,
                'user_id' => auth()->id(),
            ]);
        });
        static::updated(function (MailProfile $profile): void {
            \Log::info('mail_profile.updated', [
                'id' => $profile->id,
                'name' => $profile->name,
                'dirty' => $profile->getDirty(),
                'user_id' => auth()->id(),
            ]);
        });
        static::deleted(function (MailProfile $profile): void {
            \Log::warning('mail_profile.deleted', [
                'id' => $profile->id,
                'name' => $profile->name,
                'user_id' => auth()->id(),
            ]);
        });
    }

    public function failoverTo()
    {
        return $this->belongsTo(self::class, 'failover_to_id');
    }

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

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

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