<?php

namespace Tests\Feature;

use App\Enums\UserRole;
use App\Models\AjoGroup;
use App\Models\Business;
use App\Models\User;
use App\Support\CurrentBusiness;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class TenantIsolationTest extends TestCase
{
    use RefreshDatabase;

    public function test_business_scope_hides_other_business_records(): void
    {
        $first = Business::create(['name' => 'First', 'slug' => 'first']);
        $second = Business::create(['name' => 'Second', 'slug' => 'second']);
        app(CurrentBusiness::class)->set($second);

        $foreignGroup = AjoGroup::create([
            'name' => 'Private Group',
            'contribution_type' => 'monthly',
            'contribution_amount' => 100000,
            'maximum_members' => 10,
            'start_date' => today(),
            'status' => 'active',
        ]);

        app(CurrentBusiness::class)->set($first);

        $this->assertNull(AjoGroup::find($foreignGroup->id));
        $this->assertSame(0, AjoGroup::count());
    }

    public function test_policy_rejects_cross_business_access(): void
    {
        $first = Business::create(['name' => 'First', 'slug' => 'first']);
        $second = Business::create(['name' => 'Second', 'slug' => 'second']);
        $user = User::factory()->create(['business_id' => $first->id, 'role' => UserRole::Owner]);
        app(CurrentBusiness::class)->set($second);
        $group = AjoGroup::create(['name' => 'Private', 'contribution_type' => 'weekly', 'contribution_amount' => 50000, 'maximum_members' => 5, 'start_date' => today(), 'status' => 'active']);

        $this->assertFalse($user->can('view', $group));
    }
}
