<?php

namespace Tests\Feature;

use App\Models\Branch;
use App\Models\Customer;
use App\Models\FinancialYear;
use App\Models\Role;
use App\Models\Sale;
use App\Models\User;
use App\Models\Warehouse;
use App\Services\BranchAccessService;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use RuntimeException;
use Tests\TestCase;

class SecurityAndBranchAccessTest extends TestCase
{
    use RefreshDatabase;

    public function test_permissions_and_branch_scope_are_enforced_server_side(): void
    {
        $this->seed(DatabaseSeeder::class);
        $secondBranch = Branch::create(['code' => 'DMM', 'name_en' => 'Dammam Branch', 'name_ar' => 'فرع الدمام', 'status' => 'active']);
        $secondWarehouse = Warehouse::create(['code' => 'WH-DMM', 'name_en' => 'Dammam Warehouse', 'name_ar' => 'مستودع الدمام', 'branch_id' => $secondBranch->id, 'type' => 'main', 'status' => 'active']);
        $customer = Customer::where('customer_code', 'CASH')->firstOrFail();
        $year = FinancialYear::where('is_default', true)->firstOrFail();
        Sale::withoutGlobalScopes()->create([
            'invoice_no' => 'SI-DMM-000001', 'invoice_type' => 'simplified_tax_invoice', 'customer_id' => $customer->id,
            'warehouse_id' => $secondWarehouse->id, 'branch_id' => $secondBranch->id, 'financial_year_id' => $year->id,
            'invoice_date' => '2026-08-11', 'invoice_timestamp' => now(), 'payment_type' => 'cash', 'price_mode' => 'Exclusive VAT',
            'gross_total' => 100, 'taxable_total' => 100, 'vat_total' => 15, 'grand_total' => 115,
            'paid_total' => 115, 'balance_total' => 0, 'status' => 'finalized',
        ]);

        $user = User::create(['name' => 'Jeddah Cashier', 'username' => 'cashier.jed', 'email' => 'cashier.jed@example.test', 'password' => 'Password123!', 'status' => 'active']);
        $user->roles()->attach(Role::where('slug', 'cashier')->firstOrFail());
        $user->branches()->attach(Branch::where('code', 'JED')->firstOrFail());
        $this->actingAs($user);

        $this->get(route('sales.index'))->assertOk()->assertDontSee('SI-DMM-000001');
        $this->get(route('purchases.index'))->assertForbidden();

        $this->expectException(RuntimeException::class);
        app(BranchAccessService::class)->assertWarehouse($secondWarehouse->id, $secondBranch->id, 'sales');
    }
}
