<?php

namespace Tests\Feature;

use App\Models\CashbackLedger;
use App\Models\CashbackWallet;
use App\Models\User;
use App\Services\CashbackExpiryService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CashbackExpiryServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_due_cashback_balance_expires_once_with_idempotent_reference(): void
    {
        $user = User::factory()->create();
        CashbackWallet::query()->create([
            'user_id' => $user->id,
            'balance' => 125.50,
            'last_activity_at' => now()->subDays(95),
        ]);

        /** @var CashbackExpiryService $service */
        $service = app(CashbackExpiryService::class);
        $service->updateSettings([
            'enabled' => true,
            'expiry_days' => 90,
        ]);

        $first = $service->run([
            'trigger' => 'manual',
            'as_of' => now(),
        ]);

        $this->assertSame('completed', $first['status']);
        $this->assertSame(1, (int) $first['wallets_expired']);
        $this->assertSame(125.50, (float) $first['total_expired']);
        $this->assertSame('0.00', (string) $user->fresh()->cashbackWallet->balance);
        $this->assertDatabaseHas('cashback_ledgers', [
            'user_id' => $user->id,
            'entry_type' => 'debit',
            'source' => 'expiry',
            'amount' => '125.50',
        ]);

        $second = $service->run([
            'trigger' => 'manual',
            'as_of' => now(),
        ]);

        $this->assertSame('completed', $second['status']);
        $this->assertSame(0, (int) $second['wallets_expired']);
        $this->assertSame(1, CashbackLedger::query()
            ->where('user_id', $user->id)
            ->where('source', 'expiry')
            ->count());
    }

    public function test_not_due_cashback_is_not_expired(): void
    {
        $user = User::factory()->create();
        CashbackWallet::query()->create([
            'user_id' => $user->id,
            'balance' => 80.00,
            'last_activity_at' => now()->subDays(10),
        ]);

        /** @var CashbackExpiryService $service */
        $service = app(CashbackExpiryService::class);
        $service->updateSettings([
            'enabled' => true,
            'expiry_days' => 30,
        ]);

        $result = $service->expireUserIfDue($user, [
            'as_of' => now(),
        ]);

        $this->assertSame('not_due', $result['status']);
        $this->assertSame('80.00', (string) $user->fresh()->cashbackWallet->balance);
        $this->assertDatabaseMissing('cashback_ledgers', [
            'user_id' => $user->id,
            'source' => 'expiry',
        ]);
    }
}

