<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Assessment;
use App\Models\AssessmentTemplate;
use App\Models\Branch;
use App\Models\ClinicalPathway;
use App\Models\Consultation;
use App\Models\Diagnosis;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\PatientPathway;
use App\Models\User;
use App\Models\Visit;
use App\Services\Care\CareFeatures;
use App\Services\Care\PathwayMatcher;
use App\Services\Care\PathwayService;
use Database\Seeders\AssessmentTemplateSeeder;
use Database\Seeders\ClinicalPathwaySeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Tests\TestCase;

/** PR 7 — diabetes_core + diabetes pathway. */
class CareDiabetesPathwayTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

    protected Organization $organization;

    protected Branch $branch;

    protected Patient $patient;

    protected Member $member;

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

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

        $this->organization = Organization::create([
            'owner_ref' => $this->user->public_id,
            'name' => 'DM Clinic',
            'slug' => 'dm-clinic',
            'timezone' => 'UTC',
            'settings' => [
                'onboarded' => true,
                'rollout' => [CareFeatures::ASSESSMENTS_ENGINE => true],
            ],
        ]);

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

        $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' => 'LC-DM-001',
            'first_name' => 'Abena',
            'last_name' => 'Darko',
        ]);

        $this->seed(AssessmentTemplateSeeder::class);
        $this->seed(ClinicalPathwaySeeder::class);
    }

    public function test_diabetes_pack_and_pathway_seeded(): void
    {
        $template = AssessmentTemplate::currentSystemByCode('diabetes_core');
        $this->assertNotNull($template);
        $this->assertTrue($template->questions()->where('code', 'foot_assessment')->exists());
        $this->assertTrue($template->questions()->where('code', 'hba1c')->exists());

        $pathway = ClinicalPathway::findByCode('diabetes');
        $this->assertNotNull($pathway);
        $this->assertTrue(
            $pathway->templates()->where('template_code', 'diabetes_core')->where('is_required_on_activation', true)->exists()
        );
    }

    public function test_matcher_matches_type2_and_e11(): void
    {
        $matcher = app(PathwayMatcher::class);

        $byCode = $matcher->match([['code' => 'E11.9', 'description' => '']]);
        $this->assertTrue($byCode->contains(fn ($r) => $r['pathway_code'] === 'diabetes'));

        $byKw = $matcher->match([['code' => '', 'description' => 'Type 2 diabetes mellitus']]);
        $this->assertTrue($byKw->contains(fn ($r) => $r['pathway_code'] === 'diabetes'));
    }

    public function test_activate_diabetes_creates_core_draft_and_comorbidity_with_stroke(): void
    {
        $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(),
        ]);

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

        Diagnosis::create([
            'owner_ref' => $this->user->public_id,
            'consultation_id' => $consultation->id,
            'code' => 'E11.9',
            'description' => 'Type 2 diabetes mellitus',
            'is_primary' => true,
        ]);

        $this->actingAs($this->user)
            ->post(route('care.pathways.store', $this->patient), [
                'pathway_code' => 'diabetes',
                'consultation_uuid' => $consultation->uuid,
            ])
            ->assertRedirect();

        $this->assertSame(1, PatientPathway::where('status', PatientPathway::STATUS_ACTIVE)->count());
        $this->assertTrue(
            Assessment::query()->whereHas('template', fn ($q) => $q->where('code', 'diabetes_core'))->exists()
        );

        // Comorbidity: also activate stroke
        app(PathwayService::class)->activate(
            $this->patient,
            ClinicalPathway::findByCode('stroke'),
            $this->user->public_id,
            $this->member,
            ['consultation' => $consultation, 'actor' => $this->user->public_id],
        );

        $this->assertSame(2, PatientPathway::where('status', PatientPathway::STATUS_ACTIVE)->count());
        $this->assertGreaterThanOrEqual(3, Assessment::where('status', Assessment::STATUS_DRAFT)->count()); // dm + nihss + mrs

        $this->actingAs($this->user)
            ->get(route('care.consultations.show', $consultation))
            ->assertOk()
            ->assertSee('Diabetes')
            ->assertSee('Stroke')
            ->assertSee('diabetes_core');
    }

    public function test_nurse_can_complete_diabetes_core(): void
    {
        $this->member->update(['role' => 'nurse']);

        $this->actingAs($this->user)
            ->post(route('care.assessments.store', $this->patient), ['template_code' => 'diabetes_core'])
            ->assertRedirect();

        $assessment = Assessment::first();
        $this->actingAs($this->user)
            ->put(route('care.assessments.update', $assessment), [
                'answers' => [
                    'foot_assessment' => 'normal',
                    'hba1c' => 7.2,
                    'diet_adherence' => 'good',
                ],
            ]);
        $this->actingAs($this->user)
            ->post(route('care.assessments.complete', $assessment))
            ->assertRedirect();

        $this->assertTrue($assessment->fresh()->isCompleted());
    }
}
