<?php

namespace Tests\Feature;

use App\Models\Invoice;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AdminFinancePaymentSecurityTest extends TestCase
{
    use RefreshDatabase;

    public function test_payment_rejects_customer_invoice_mismatch(): void
    {
        $admin = User::factory()->create([
            'role' => 'FINANCIAL_ACCOUNTANT',
            'email_verified_at' => now(),
        ]);

        $invoiceCustomer = User::factory()->create(['role' => 'CUSTOMER']);
        $otherCustomer = User::factory()->create(['role' => 'CUSTOMER']);

        $invoice = Invoice::create([
            'invoice_number' => 'INV-TEST-001',
            'customer_id' => $invoiceCustomer->id,
            'type' => 'SERVICE',
            'status' => 'DRAFT',
            'payment_status' => 'PENDING',
            'issue_date' => now(),
            'due_date' => now()->addDays(7),
            'subtotal' => 100,
            'tax_amount' => 0,
            'total_amount' => 100,
            'paid_amount' => 0,
        ]);

        $this->actingAs($admin)
            ->from(route('admin.finance.show', $invoice))
            ->post(route('admin.finance.payments.store'), [
                'customer_id' => $otherCustomer->id,
                'invoice_id' => $invoice->id,
                'amount' => 10,
                'payment_method' => 'CASH',
            ])
            ->assertSessionHasErrors('invoice_id');
    }

    public function test_payment_rejects_overpayment(): void
    {
        $admin = User::factory()->create([
            'role' => 'FINANCIAL_ACCOUNTANT',
            'email_verified_at' => now(),
        ]);

        $customer = User::factory()->create(['role' => 'CUSTOMER']);

        $invoice = Invoice::create([
            'invoice_number' => 'INV-TEST-002',
            'customer_id' => $customer->id,
            'type' => 'SERVICE',
            'status' => 'DRAFT',
            'payment_status' => 'PENDING',
            'issue_date' => now(),
            'due_date' => now()->addDays(7),
            'subtotal' => 100,
            'tax_amount' => 0,
            'total_amount' => 100,
            'paid_amount' => 20,
        ]);

        $this->actingAs($admin)
            ->from(route('admin.finance.show', $invoice))
            ->post(route('admin.finance.payments.store'), [
                'customer_id' => $customer->id,
                'invoice_id' => $invoice->id,
                'amount' => 200,
                'payment_method' => 'CASH',
            ])
            ->assertSessionHasErrors('amount');
    }
}
