<?php

namespace Tests\Feature;

use App\Jobs\SendSmsToCouponJob;
use App\Jobs\StartSmsCampaignJob;
use App\Models\Coupon;
use App\Models\User;
use App\Services\SmsBroadcastService;
use Illuminate\Foundation\Testing\LazilyRefreshDatabase;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;

class StartSmsCampaignJobTest extends TestCase
{
    use LazilyRefreshDatabase;

    public function test_job_is_dispatched_with_expected_payload(): void
    {
        Queue::fake();

        $admin = User::factory()->create();
        $coupon = Coupon::factory()->create();

        StartSmsCampaignJob::dispatch(
            adminId: $admin->id,
            message: 'Hello',
            sendToAll: false,
            selectedIds: [$coupon->id],
            excludedIds: [],
        );

        Queue::assertPushed(StartSmsCampaignJob::class, function (StartSmsCampaignJob $job) use ($admin, $coupon): bool {
            return $job->adminId === $admin->id
                && $job->message === 'Hello'
                && $job->sendToAll === false
                && $job->selectedIds === [$coupon->id]
                && $job->excludedIds === [];
        });
    }

    public function test_handle_starts_campaign_and_chains_send_jobs(): void
    {
        Bus::fake();

        $admin = User::factory()->create();
        $coupons = Coupon::factory()->count(2)->create();

        $job = new StartSmsCampaignJob(
            adminId: $admin->id,
            message: 'Test broadcast',
            sendToAll: false,
            selectedIds: $coupons->pluck('id')->all(),
        );

        $job->handle(app(SmsBroadcastService::class));

        Bus::assertChained([
            SendSmsToCouponJob::class,
            SendSmsToCouponJob::class,
        ]);
    }
}
