<?php
namespace Tests\Feature;

use App\Models\Currency;
use App\Models\Customer;
use App\Models\SalesInvoice;
use App\Services\CurrencyService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CurrencyTest extends TestCase {
    use RefreshDatabase;

    public function test_base_rate_is_one_without_rows(): void {
        $this->assertSame(1.0, CurrencyService::rate('GHS'));
        $this->assertSame(1.0, CurrencyService::rate('ghs'));
    }

    public function test_inactive_currency_throws(): void {
        Currency::create(['code' => 'USD', 'name' => 'US Dollar', 'symbol' => '$', 'rate_to_ghs' => 15.5, 'is_active' => false]);
        $this->expectException(\RuntimeException::class);
        CurrencyService::rate('USD');
    }

    public function test_to_ghs_rounds_to_pesewas(): void {
        $this->assertSame(1540.5, CurrencyService::toGhs(100, 15.405));
        $this->assertSame(853.3, round(CurrencyService::toGhs(2438, 15.75) - CurrencyService::toGhs(2438, 15.40), 2));
    }

    public function test_sum_ghs_converts_mixed_currencies(): void {
        $c = Customer::create(['code' => 'C-T1', 'name' => 'FX Test Customer']);
        SalesInvoice::create(['invoice_no' => 'INV-T-1', 'invoice_date' => '2026-09-01', 'customer_id' => $c->id,
            'grand_total' => 100, 'balance_due' => 100]); // GHS @ 1
        SalesInvoice::create(['invoice_no' => 'INV-T-2', 'invoice_date' => '2026-09-01', 'customer_id' => $c->id,
            'grand_total' => 100, 'balance_due' => 100, 'currency_code' => 'USD', 'exchange_rate' => 15.5]);
        $this->assertSame(1650.0, CurrencyService::sumGhs(SalesInvoice::query(), 'balance_due'));
    }

    public function test_sum_ghs_plain_table_unaffected(): void {
        Currency::create(['code' => 'USD', 'name' => 'US Dollar', 'symbol' => '$', 'rate_to_ghs' => 15.5]);
        Currency::create(['code' => 'EUR', 'name' => 'Euro', 'symbol' => '€', 'rate_to_ghs' => 16.75]);
        // currencies has no exchange_rate column → plain sum
        $this->assertSame(32.25, CurrencyService::sumGhs(Currency::query(), 'rate_to_ghs'));
    }

    public function test_sum_ghs_collection(): void {
        $rows = collect([(object) ['amount' => 100, 'exchange_rate' => 1], (object) ['amount' => 100, 'exchange_rate' => 15.5]]);
        $this->assertSame(1650.0, CurrencyService::sumGhs($rows, 'amount'));
    }

    public function test_doc_ghs_uses_snapshot_rate(): void {
        $inv = (object) ['grand_total' => 6095.00, 'exchange_rate' => 15.40];
        $this->assertSame(93863.0, CurrencyService::docGhs($inv, 'grand_total'));
    }
}
