<?php

namespace Tests\Feature;

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

class PatientCrmTest extends TestCase
{
    use RefreshDatabase;

    protected Tenant $tenant;
    protected User $owner;
    protected string $base;

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

        $this->tenant = Tenant::create(['name' => 'Smile', 'slug' => 'smile']);
        $this->tenant->subscription()->create([
            'plan_id' => \App\Models\Plan::first()->id,
            'status' => 'trialing',
            'starts_at' => now(),
            'current_period_ends_at' => now()->addDays(14),
        ]);

        app(Tenancy::class)->set($this->tenant);
        $this->owner = User::withoutEvents(fn () => User::create([
            'tenant_id' => $this->tenant->id, 'name' => 'Owner',
            'email' => 'o@example.com', 'password' => 'password123',
        ]));
        $this->owner->assignRole('clinic_owner');
        app(Tenancy::class)->forget();

        $this->base = 'http://smile.'.config('tenancy.central_domain');
    }

    public function test_owner_can_create_and_search_patients(): void
    {
        $this->actingAs($this->owner)
            ->post($this->base.'/patients', [
                'full_name' => 'Sara Kareem', 'phone' => '07709998877',
            ])->assertRedirect();

        $this->actingAs($this->owner)
            ->get($this->base.'/patients?q=0770999')
            ->assertOk()->assertSee('Sara Kareem');

        $this->actingAs($this->owner)
            ->get($this->base.'/patients?q=Sara')
            ->assertOk()->assertSee('Sara Kareem');
    }

    public function test_patients_from_another_clinic_are_invisible(): void
    {
        $other = Tenant::create(['name' => 'Other', 'slug' => 'other']);
        app(Tenancy::class)->set($other);
        Patient::factory()->create(['full_name' => 'Hidden Patient']);
        app(Tenancy::class)->forget();

        $this->actingAs($this->owner)
            ->get($this->base.'/patients')
            ->assertOk()->assertDontSee('Hidden Patient');
    }

    public function test_receptionist_cannot_manage_dentists(): void
    {
        app(Tenancy::class)->set($this->tenant);
        $receptionist = User::withoutEvents(fn () => User::create([
            'tenant_id' => $this->tenant->id, 'name' => 'Reception',
            'email' => 'r@example.com', 'password' => 'password123',
        ]));
        $receptionist->assignRole('receptionist');
        app(Tenancy::class)->forget();

        $this->actingAs($receptionist)
            ->post($this->base.'/dentists', ['name' => 'Dr. X', 'color' => '#000000',
                'slot_duration_min' => 30, 'buffer_min' => 0, 'status' => 'active'])
            ->assertForbidden();
    }
}
