<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class EmailSubscriber extends Model
{
    protected $fillable = [
        'email',
        'name',
        'subscribed_at',
        'unsubscribed_at',
        'is_active',
        'ip_address',
        'confirmation_token',
        'confirmed_at',
    ];

    protected $casts = [
        'subscribed_at'   => 'datetime',
        'unsubscribed_at' => 'datetime',
        'confirmed_at'    => 'datetime',
        'is_active'       => 'boolean',
    ];

    /**
     * Auto-generate a unique UUID confirmation_token on creation.
     */
    protected static function booted(): void
    {
        static::creating(function (self $subscriber) {
            if (empty($subscriber->confirmation_token)) {
                $subscriber->confirmation_token = Str::uuid()->toString();
            }
        });
    }

    /**
     * Scope: active subscribers (is_active=true and not unsubscribed).
     */
    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true)->whereNull('unsubscribed_at');
    }

    /**
     * Scope: confirmed subscribers (confirmed_at is not null).
     */
    public function scopeConfirmed(Builder $query): Builder
    {
        return $query->whereNotNull('confirmed_at');
    }
}
