<?php

namespace Tests\Unit\Services\Payments;

use App\Services\Payments\PaymentTransactionService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;

class PaymentTransactionServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_create_and_update_transaction(): void
    {
        if (!Schema::hasColumn('payment_transactions', 'payment_reference')) {
            Schema::table('payment_transactions', function (Blueprint $table) {
                $table->string('payment_reference')->nullable();
            });
        }

        if (!Schema::hasColumn('payment_transactions', 'is_full_payment')) {
            Schema::table('payment_transactions', function (Blueprint $table) {
                $table->boolean('is_full_payment')->default(0);
            });
        }

        DB::table('payments')->insert([
            'id' => 1,
            'parent_id' => 10,
            'invoice_id' => 1,
            'total_amount' => 100,
            'paid_amount' => 0,
            'balance' => 100,
            'number_of_installments' => 1,
            'payment_method' => 'card',
            'payment_date' => '2025-01-01',
            'school_year' => '2025-2026',
            'status' => 'Pending',
        ]);

        $service = new PaymentTransactionService();
        $transaction = $service->create([
            'transaction_id' => 'TXN-1',
            'payment_id' => 1,
            'transaction_date' => '2025-01-02 00:00:00',
            'amount' => 50,
            'payment_method' => 'card',
            'payment_status' => 'Pending',
            'transaction_fee' => 1.25,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
        ]);

        $this->assertSame('TXN-1', $transaction->transaction_id);

        $updated = $service->updateStatus('TXN-1', 'Completed');

        $this->assertTrue($updated);
        $this->assertDatabaseHas('payment_transactions', [
            'transaction_id' => 'TXN-1',
            'payment_status' => 'Completed',
        ]);
    }
}
