<?php

namespace App\Models;

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

class Mailbox extends Model
{
    /** @use HasFactory<\Database\Factories\MailboxFactory> */
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'mailbox_hash',
        'domain_hash',
        'user_id',
        'session_id',
        'address',
        'type',
        'created_ip',
        'last_accessed_ip',
        'last_accessed_at',
        'is_blocked',
        'block_reason',
        'blocked_at',
        'expires_at',
    ];

    protected function casts(): array
    {
        return [
            'is_blocked' => 'boolean',
            'last_accessed_at' => 'datetime',
            'blocked_at' => 'datetime',
            'expires_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (Mailbox $mailbox) {
            if (empty($mailbox->mailbox_hash)) {
                $mailbox->mailbox_hash = bin2hex(random_bytes(32));
            }

            // Record creation analytics
            \App\Jobs\TrackAnalytics::dispatch(
                eventType: 'mailbox_created',
                mailboxHash: $mailbox->mailbox_hash,
                domainHash: $mailbox->domain_hash,
                userId: $mailbox->user_id,
                userType: $mailbox->user_id ? 'authenticated' : 'guest',
                ipAddress: request()->ip(),
                userAgent: request()->userAgent()
            );
        });

        static::deleted(function (Mailbox $mailbox) {
            // Find all associated emails
            $hashes = \App\Models\Email::where('recipient_email', $mailbox->address)->pluck('unique_id_hash');

            if ($hashes->isNotEmpty()) {
                // Clean MongoDB documents
                \App\Models\EmailBody::whereIn('unique_id_hash', $hashes)->delete();

                // Clean MariaDB records
                \App\Models\Email::whereIn('unique_id_hash', $hashes)->delete();

                // Future Placeholder: Delete physical attachments from S3/Storage here
            }
        });
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function emails()
    {
        return $this->hasMany(Email::class, 'recipient_email', 'address');
    }

    public function domain()
    {
        return $this->belongsTo(Domain::class, 'domain_hash', 'domain_hash');
    }
}
