<?php

namespace Tests\Feature;

use App\Models\Plan;
use App\Models\Tenant;
use App\Models\User;
use App\Support\Tenancy;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class TenancyIsolationTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed();
    }

    public function test_global_scope_hides_other_tenants_records(): void
    {
        $a = Tenant::create(['name' => 'Clinic A', 'slug' => 'clinic-a']);
        $b = Tenant::create(['name' => 'Clinic B', 'slug' => 'clinic-b']);

        User::withoutEvents(fn () => User::create([
            'tenant_id' => $a->id, 'name' => 'Owner A',
            'email' => 'a@example.com', 'password' => 'password123',
        ]));
        User::withoutEvents(fn () => User::create([
            'tenant_id' => $b->id, 'name' => 'Owner B',
            'email' => 'b@example.com', 'password' => 'password123',
        ]));

        app(Tenancy::class)->set($a);

        $this->assertSame(1, User::count());
        $this->assertSame('a@example.com', User::first()->email);
        $this->assertNull(User::where('email', 'b@example.com')->first());
    }

    public function test_tenant_id_is_autofilled_on_create(): void
    {
        $tenant = Tenant::create(['name' => 'Clinic C', 'slug' => 'clinic-c']);
        app(Tenancy::class)->set($tenant);

        $user = User::withoutEvents(fn () => User::create([
            'name' => 'Dr C', 'email' => 'c@example.com', 'password' => 'password123',
        ]));

        $this->assertSame($tenant->id, $user->tenant_id);
    }

    public function test_unknown_subdomain_is_404(): void
    {
        $this->get('http://nope.'.config('tenancy.central_domain').'/dashboard')
            ->assertNotFound();
    }
}
