<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Models\GlobalTransaction;
use App\Models\User;
use App\Enums\Market\ProductTransactionType;
use App\Enums\Market\TransactionFlow;
use Tests\TestCase;
use Hypervel\Support\Facades\Auth;
use Hypervel\Foundation\Testing\RefreshDatabase;

class GlobalTransactionFlowTest extends TestCase
{
    use RefreshDatabase;

    public function test_transaction_creation_assigns_correct_flow()
    {
        $user = factory(User::class)->create();

        Auth::login($user);

        // Test INCOME flow (STORE_SALE)
        $response = $this->post('/admin/transactions/create', [
            'amount' => 100,
            'type' => ProductTransactionType::STORE_SALE->value,
            'description' => 'Test Sale'
        ]);

        $response->assertStatus(200);
        $hashkey = $response->json('hashkey');
        
        $transaction = GlobalTransaction::where('hashkey', $hashkey)->first();
        $this->assertEquals(TransactionFlow::INCOME, $transaction->flow);

        // Test EXPENSE flow (PURCHASE)
        $response = $this->post('/admin/transactions/create', [
            'amount' => 50,
            'type' => ProductTransactionType::PURCHASE->value,
            'description' => 'Test Purchase'
        ]);

        $response->assertStatus(200);
        $hashkey = $response->json('hashkey');
        
        $transaction = GlobalTransaction::where('hashkey', $hashkey)->first();
        $this->assertEquals(TransactionFlow::EXPENSE, $transaction->flow);

        // Test NEUTRAL flow (INVENTORY_ADJUSTMENT)
        $response = $this->post('/admin/transactions/create', [
            'amount' => 0,
            'type' => ProductTransactionType::INVENTORY_ADJUSTMENT->value,
            'description' => 'Test Adjustment'
        ]);

        $response->assertStatus(200);
        $hashkey = $response->json('hashkey');
        
        $transaction = GlobalTransaction::where('hashkey', $hashkey)->first();
        $this->assertEquals(TransactionFlow::NEUTRAL, $transaction->flow);
    }

    public function test_transaction_list_returns_flow_data()
    {
        $user = factory(User::class)->create();
        Auth::login($user);

        $response = $this->post('/admin/transactions/list');
        $response->assertStatus(200);
        
        $data = $response->json();
        if (count($data) > 0) {
            $this->assertArrayHasKey('flow', $data[0]);
            $this->assertArrayHasKey('value', $data[0]['flow']);
            $this->assertArrayHasKey('label', $data[0]['flow']);
        }
    }
}
