<?php

namespace Tests\Unit\Services\Payments;

use App\Services\EmailService;
use App\Services\Payments\PaypalPaymentSyncService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Mockery;
use Tests\TestCase;

class PaypalPaymentSyncServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_sync_applies_payment_and_marks_synced(): void
    {
        DB::table('configuration')->insert([
            ['config_key' => 'school_year', 'config_value' => '2024-2025'],
            ['config_key' => 'semester', 'config_value' => 'Spring'],
        ]);

        DB::table('users')->insert([
            'id' => 1,
            'school_id' => 123,
            'firstname' => 'Parent',
            'lastname' => 'User',
            'email' => 'parent@example.com',
            'status' => 'Active',
        ]);

        DB::table('invoices')->insert([
            'id' => 1,
            'parent_id' => 1,
            'invoice_number' => 'INV-1',
            'total_amount' => 100,
            'balance' => 100,
            'paid_amount' => 0,
            'status' => 'Unpaid',
            'school_year' => '2024-2025',
            'semester' => 'Spring',
            'issue_date' => '2025-01-01',
        ]);

        DB::table('paypal_payments')->insert([
            'id' => 1,
            'parent_school_id' => 123,
            'transaction_id' => 'TXN-1',
            'status' => 'COMPLETED',
            'amount' => 50,
            'synced' => 0,
            'sync_attempts' => 0,
            'created_at' => '2025-01-15 10:00:00',
        ]);

        $email = Mockery::mock(EmailService::class);
        $email->shouldReceive('send')->once()->andReturn(true);

        $service = new PaypalPaymentSyncService($email);
        $result = $service->sync(false, false);

        $this->assertSame(1, $result['processed']);
        $this->assertDatabaseHas('paypal_payments', [
            'id' => 1,
            'synced' => 1,
        ]);
        $this->assertDatabaseHas('payments', [
            'invoice_id' => 1,
            'parent_id' => 1,
            'paid_amount' => 50,
        ]);
        $this->assertDatabaseHas('invoices', [
            'id' => 1,
            'balance' => 50,
        ]);
    }
}
