<?php

namespace App\Models\Contact;

use App\Enum\Contact\BulkEmailCampaignStatus;
use App\Models\Solicitor\SolicitorEmailSender;
use App\Models\User\User;
use App\Trait\BelongsToSolicitor;
use App\ValueObjects\Communications\DispatchResult;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class BulkEmailCampaign extends Model
{
    use BelongsToSolicitor;

    protected $fillable = [
        'solicitor_id',
        'template_id',
        'sender_email_id',
        'filters',
        'status',
        'total_recipients',
        'queued_count',
        'suppressed_count',
        'deduped_count',
        'rate_limited_count',
        'failed_count',
        'processed_count',
        'created_by',
        'started_at',
        'completed_at',
        'last_error',
    ];

    protected $casts = [
        'filters' => 'array',
        'status' => BulkEmailCampaignStatus::class,
        'started_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    public function template(): BelongsTo
    {
        return $this->belongsTo(ContactTemplate::class, 'template_id');
    }

    public function sender(): BelongsTo
    {
        return $this->belongsTo(SolicitorEmailSender::class, 'sender_email_id');
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Tally one per-recipient dispatch result onto the campaign counters.
     */
    public function incrementResult(DispatchResult $result): void
    {
        $column = match (true) {
            $result->queued => 'queued_count',
            $result->wasSuppressed => 'suppressed_count',
            $result->wasDeduped => 'deduped_count',
            $result->wasRateLimited => 'rate_limited_count',
            default => 'failed_count',
        };

        $this->increment($column);
        $this->increment('processed_count');
    }
}
