<?php

namespace Spatie\Mailcoach\Domain\Automation\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Spatie\Mailcoach\Domain\Audience\Models\Subscriber;
use Spatie\Mailcoach\Domain\Automation\Models\Automation;
use Spatie\Mailcoach\Domain\Shared\Traits\UsesMailcoachModels;

class TriggerAutomationForAllSubscribersJob implements ShouldBeUnique, ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;
    use UsesMailcoachModels;

    public function __construct(public Automation $automation) {}

    public function uniqueId(): string
    {
        return (string) $this->automation->id;
    }

    public function handle(): void
    {
        $this->automation->newSubscribersQuery()
            ->lazyById()
            ->each(function (Subscriber $subscriber) {
                dispatch(new RunAutomationForSubscriberJob($this->automation, $subscriber));
            });
    }
}
