<?php

namespace Tests\Feature\Api\V1\Finance;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class PaypalTransactionsControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_index_returns_transactions(): void
    {
        $this->seedUsers();
        Sanctum::actingAs(User::query()->findOrFail(1));

        DB::table('paypal_payments')->insert([
            'id' => 1,
            'transaction_id' => 'PP-1001',
            'order_id' => 'ORDER-1',
            'parent_school_id' => 10,
            'payer_email' => 'payer@example.com',
            'amount' => 50,
            'net_amount' => 48,
            'currency' => 'USD',
            'status' => 'COMPLETED',
            'event_type' => 'PAYMENT.SALE.COMPLETED',
            'created_at' => '2025-01-01 10:00:00',
        ]);

        $response = $this->getJson('/api/v1/finance/paypal-transactions');

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $this->assertNotEmpty($response->json('transactions'));
    }

    public function test_csv_download(): void
    {
        $this->seedUsers();
        Sanctum::actingAs(User::query()->findOrFail(1));

        DB::table('paypal_payments')->insert([
            'id' => 1,
            'transaction_id' => 'PP-1002',
            'order_id' => 'ORDER-2',
            'parent_school_id' => 10,
            'payer_email' => 'payer@example.com',
            'amount' => 60,
            'net_amount' => 58,
            'currency' => 'USD',
            'status' => 'COMPLETED',
            'event_type' => 'PAYMENT.SALE.COMPLETED',
            'created_at' => '2025-01-01 10:00:00',
        ]);

        $response = $this->get('/api/v1/finance/paypal-transactions/csv');

        $response->assertOk();
        $response->assertHeader('Content-Type', 'text/csv; charset=utf-8');
    }

    private function seedUsers(): void
    {
        DB::table('roles')->insert([
            ['id' => 1, 'name' => 'admin', 'slug' => 'admin', 'is_active' => 1],
        ]);

        DB::table('users')->insert([
            'id' => 1,
            'school_id' => 1,
            'firstname' => 'Admin',
            'lastname' => 'User',
            'cellphone' => '5555555555',
            'email' => 'admin@example.com',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'is_verified' => 1,
            'status' => 'Active',
            'is_suspended' => 0,
            'failed_attempts' => 0,
            'password' => bcrypt('secret'),
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        DB::table('user_roles')->insert([
            'user_id' => 1,
            'role_id' => 1,
        ]);
    }
}
