<?php

namespace Tests\Feature;

use App\Models\Item;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AutoCloseTransactionsTest extends TestCase
{
    use RefreshDatabase;

    private function transaction(array $overrides = []): Transaction
    {
        $seller = User::factory()->create();
        $buyer = User::factory()->create();
        $item = Item::create([
            'user_id' => $seller->id,
            'title' => 'Test Synth',
            'description' => 'A synth',
            'price' => 100,
            'condition' => 'Good',
            'quantity' => 1,
            'listing_type' => 'sale',
            'status' => 'sold',
            'location_country' => 'US',
        ]);

        return Transaction::create(array_merge([
            'item_id' => $item->id,
            'seller_id' => $seller->id,
            'buyer_id' => $buyer->id,
            'price' => 100,
            'status' => 'pending',
            'type' => 'sale',
            'auto_close_at' => now()->subDay(),
        ], $overrides));
    }

    public function test_overdue_pending_transactions_are_completed(): void
    {
        $overdue = $this->transaction();
        $notYetDue = $this->transaction(['auto_close_at' => now()->addWeek()]);
        $alreadyDone = $this->transaction(['status' => 'completed']);

        $this->artisan('transactions:auto-close')
            ->expectsOutputToContain('Auto-closed 1 transaction(s).')
            ->assertSuccessful();

        $this->assertSame('completed', $overdue->fresh()->status);
        $this->assertNotNull($overdue->fresh()->completed_at);
        $this->assertSame('pending', $notYetDue->fresh()->status);
    }
}
