<?php

use App\Jobs\PackageItemSmsJob;
use App\Models\Package;
use App\Models\SmsLog;
use App\Models\SmsProfile;
use App\Services\Sms\SmsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;

uses(RefreshDatabase::class);

it('processes a queued package item and updates counters', function () {
    $package = Package::create([
        'uuid' => (string) Str::uuid(),
        'type' => Package::TYPE_SMS,
        'status' => Package::STATUS_DRAFT,
        'name' => 'Test SMS Package',
        'total_items' => 1,
    ]);

    $profile = SmsProfile::factory()->create();

    $item = $package->items()->create([
        'status' => 'queued',
        'target_json' => ['number' => '+38640123456'],
        'payload_json' => ['profile_id' => $profile->id, 'body' => 'Hello world'],
    ]);

    // Mock SmsService to return a successful log
    $log = new SmsLog([
        'status' => 'sent',
        'provider_message_id' => 'abc123',
        'cost' => 0.0100,
        'currency' => 'EUR',
        'meta' => ['parts' => 1],
    ]);

    $this->mock(SmsService::class)
        ->shouldReceive('sendFromTemplate')->zeroOrMoreTimes()
        ->andReturn($log);
    $this->mock(SmsService::class)
        ->shouldReceive('sendRaw')->zeroOrMoreTimes()
        ->andReturn($log);

    $job = new PackageItemSmsJob($item->id);
    $job->handle(app(SmsService::class));

    $item->refresh();
    $package->refresh();

    expect($item->status)->toBe('sent');
    expect($package->sent_count)->toBe(1);
    expect($package->failed_count)->toBe(0);
});
