<?php
namespace Tests\Unit;

use App\Http\Controllers\BankImportController;
use PHPUnit\Framework\TestCase;

class BankImportParserTest extends TestCase {
    private function csv(string $body): string {
        $f = tempnam(sys_get_temp_dir(), 'stmt').'.csv';
        file_put_contents($f, $body);
        return $f;
    }

    public function test_debit_credit_columns(): void {
        $rows = BankImportController::parseCsv($this->csv(
            "Date,Description,Debit,Credit,Balance\n07/09/2026,INWARD TRANSFER,,22015.14,150000.00\n06/09/2026,LEDGER FEE,150.00,,\n"));
        $this->assertCount(2, $rows);
        $this->assertSame(['date' => '2026-09-07', 'direction' => 'Cr', 'amount' => 22015.14],
            ['date' => $rows[0]['date'], 'direction' => $rows[0]['direction'], 'amount' => $rows[0]['amount']]);
        $this->assertSame('Dr', $rows[1]['direction']);
        $this->assertSame(150.0, $rows[1]['amount']);
    }

    public function test_single_amount_column_with_negatives(): void {
        $rows = BankImportController::parseCsv($this->csv(
            "Date,Narration,Amount\n2026-09-05,SALARY CREDIT,12500\n2026-09-06,ATM CASH,-2000\n"));
        $this->assertCount(2, $rows);
        $this->assertSame('Cr', $rows[0]['direction']);
        $this->assertSame('Dr', $rows[1]['direction']);
        $this->assertSame(2000.0, $rows[1]['amount']);
    }

    public function test_date_formats_and_junk_rows(): void {
        $rows = BankImportController::parseCsv($this->csv(
            "Some bank export header line\nDate,Particulars,Debit,Credit\n05-Sep-26,CHEQUE 412,5200,,\n,,\n31/12/2026,INTEREST,,12.5\n"));
        $this->assertCount(2, $rows);
        $this->assertSame('2026-09-05', $rows[0]['date']);
        $this->assertSame('2026-12-31', $rows[1]['date']);
    }

    public function test_parenthesised_and_currency_amounts(): void {
        $rows = BankImportController::parseCsv($this->csv("Date,Desc,Debit,Credit\n01/09/2026,REVERSAL,\"GH₵ 1,250.00\",\n"));
        $this->assertCount(1, $rows);
        $this->assertSame(1250.0, $rows[0]['amount']);
    }
}
