<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Branch;
use App\Models\Consultation;
use App\Models\InvestigationRequest;
use App\Models\InvestigationType;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\Prescription;
use App\Models\User;
use App\Models\Visit;
use App\Services\Care\CareFeatures;
use App\Services\Care\ConsultationReturnContext;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Tests\TestCase;

class CareConsultationReturnContextTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

    protected Organization $organization;

    protected Branch $branch;

    protected Patient $patient;

    protected Consultation $consultation;

    protected Visit $visit;

    protected function setUp(): void
    {
        parent::setUp();
        $this->withoutMiddleware(EnsurePlatformSession::class);

        $this->user = User::create([
            'public_id' => 'return-ctx-user',
            'name' => 'Doctor',
            'email' => 'return-ctx@example.com',
        ]);

        $this->organization = Organization::create([
            'owner_ref' => $this->user->public_id,
            'name' => 'Return Clinic',
            'slug' => 'return-clinic',
            'timezone' => 'UTC',
            'settings' => [
                'onboarded' => true,
                'plan' => 'pro',
                'plan_expires_at' => now()->addMonth()->toIso8601String(),
                'rollout' => [
                    CareFeatures::ASSESSMENTS_ENGINE => true,
                ],
            ],
        ]);

        Member::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'user_ref' => $this->user->public_id,
            'role' => 'hospital_admin',
        ]);

        $this->branch = Branch::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'name' => 'Main',
            'is_active' => true,
        ]);

        $this->patient = Patient::create([
            'uuid' => (string) Str::uuid(),
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_number' => 'P-RET-1',
            'first_name' => 'Ada',
            'last_name' => 'Lovelace',
        ]);

        $this->visit = Visit::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_id' => $this->patient->id,
            'status' => Visit::STATUS_OPEN,
            'checked_in_at' => now(),
        ]);

        $this->consultation = Consultation::create([
            'owner_ref' => $this->user->public_id,
            'visit_id' => $this->visit->id,
            'patient_id' => $this->patient->id,
            'status' => Consultation::STATUS_DRAFT,
            'started_at' => now(),
        ]);
    }

    public function test_consultation_show_remembers_return_context(): void
    {
        $this->actingAs($this->user)
            ->get(route('care.consultations.show', $this->consultation))
            ->assertOk()
            ->assertSessionHas(ConsultationReturnContext::SESSION_KEY, $this->consultation->uuid);
    }

    public function test_nested_pages_show_back_to_consultation_when_context_present(): void
    {
        $type = InvestigationType::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'name' => 'CBC',
            'category' => 'haematology',
            'code' => 'cbc',
            'is_active' => true,
        ]);

        $lab = InvestigationRequest::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_id' => $this->patient->id,
            'visit_id' => $this->visit->id,
            'consultation_id' => $this->consultation->id,
            'investigation_type_id' => $type->id,
            'status' => InvestigationRequest::STATUS_PENDING,
            'priority' => 'routine',
        ]);

        $rx = Prescription::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'visit_id' => $this->visit->id,
            'consultation_id' => $this->consultation->id,
            'patient_id' => $this->patient->id,
            'status' => Prescription::STATUS_ACTIVE,
        ]);

        $this->actingAs($this->user)
            ->withSession([ConsultationReturnContext::SESSION_KEY => $this->consultation->uuid])
            ->get(route('care.lab.requests.show', [
                'investigation' => $lab,
                'from_consultation' => $this->consultation->uuid,
            ]))
            ->assertOk()
            ->assertSee('Back to consultation')
            ->assertSee('Continue consultation')
            ->assertSee('Ada Lovelace');

        $this->actingAs($this->user)
            ->withSession([ConsultationReturnContext::SESSION_KEY => $this->consultation->uuid])
            ->get(route('care.prescriptions.show', [
                'prescription' => $rx,
                'from_consultation' => $this->consultation->uuid,
            ]))
            ->assertOk()
            ->assertSee('Back to consultation');

        $this->actingAs($this->user)
            ->withSession([ConsultationReturnContext::SESSION_KEY => $this->consultation->uuid])
            ->get(route('care.pathways.index', [
                'patient' => $this->patient,
                'from_consultation' => $this->consultation->uuid,
            ]))
            ->assertOk()
            ->assertSee('Back to consultation');

        $this->actingAs($this->user)
            ->get(route('care.prescriptions.create', $this->consultation))
            ->assertOk()
            ->assertSee('Back to consultation');
    }

    public function test_direct_access_without_context_hides_consultation_chrome(): void
    {
        $type = InvestigationType::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'name' => 'CBC',
            'category' => 'haematology',
            'code' => 'cbc2',
            'is_active' => true,
        ]);

        $lab = InvestigationRequest::create([
            'owner_ref' => $this->user->public_id,
            'organization_id' => $this->organization->id,
            'branch_id' => $this->branch->id,
            'patient_id' => $this->patient->id,
            'visit_id' => $this->visit->id,
            'consultation_id' => $this->consultation->id,
            'investigation_type_id' => $type->id,
            'status' => InvestigationRequest::STATUS_PENDING,
            'priority' => 'routine',
        ]);

        $this->actingAs($this->user)
            ->get(route('care.lab.requests.show', $lab))
            ->assertOk()
            ->assertDontSee('Back to consultation')
            ->assertDontSee('Continue consultation');

        $this->actingAs($this->user)
            ->get(route('care.pathways.index', $this->patient))
            ->assertOk()
            ->assertDontSee('Back to consultation');
    }

    public function test_completing_consultation_clears_return_context(): void
    {
        $this->actingAs($this->user)
            ->withSession([ConsultationReturnContext::SESSION_KEY => $this->consultation->uuid])
            ->post(route('care.consultations.complete', $this->consultation))
            ->assertRedirect(route('care.appointments.index'))
            ->assertSessionMissing(ConsultationReturnContext::SESSION_KEY);
    }
}
