<?php

declare(strict_types=1);

namespace App\Domain\Email\Models;

use App\Domain\Account\Models\Account;
use Database\Factories\EmailAccountFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class EmailAccount extends Model
{
    /** @use HasFactory<EmailAccountFactory> */
    use HasFactory, SoftDeletes;

    protected $table = 'email_accounts';

    protected $fillable = [
        'account_id', 'local', 'domain', 'password_hash',
        'quota_mb', 'usage_bytes', 'status', 'auto_create_dirs',
        'dovecot_uid', 'dovecot_gid', 'home_dir', 'enabled', 'last_login_at',
    ];

    protected $hidden = ['password_hash'];

    protected function casts(): array
    {
        return [
            'quota_mb' => 'integer',
            'usage_bytes' => 'integer',
            'auto_create_dirs' => 'boolean',
            'dovecot_uid' => 'integer',
            'dovecot_gid' => 'integer',
            'enabled' => 'boolean',
            'last_login_at' => 'datetime',
        ];
    }

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

    public function autoresponders(): HasMany
    {
        return $this->hasMany(EmailAutoresponder::class);
    }

    public function getEmailAttribute(): string
    {
        return $this->local.'@'.$this->domain;
    }

    public function usagePercent(): ?float
    {
        if ($this->quota_mb === -1) {
            return null;
        }
        $quotaBytes = $this->quota_mb * 1024 * 1024;

        return $quotaBytes ? round(($this->usage_bytes / $quotaBytes) * 100, 1) : 0;
    }
}
