<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Laravel\Cashier\Subscription;

class WinbackRecipient extends Model
{
    use HasFactory;

    protected $fillable = [
        'campaign_id',
        'user_id',
        'subscription_id',
        'current_email_index',
        'last_email_sent_at',
        'opened_count',
        'clicked_count',
        'reactivated',
        'reactivated_at',
        'unsubscribed_at',
    ];

    protected function casts(): array
    {
        return [
            'current_email_index' => 'integer',
            'opened_count' => 'integer',
            'clicked_count' => 'integer',
            'reactivated' => 'boolean',
            'last_email_sent_at' => 'datetime',
            'reactivated_at' => 'datetime',
            'unsubscribed_at' => 'datetime',
        ];
    }

    public function campaign(): BelongsTo
    {
        return $this->belongsTo(WinbackCampaign::class, 'campaign_id');
    }

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

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

    public function isActive(): bool
    {
        if ($this->unsubscribed_at !== null) {
            return false;
        }

        if ($this->reactivated) {
            return false;
        }

        return $this->campaign->status === 'active';
    }
}
