<?php

namespace Tests\Feature;

use App\Models\AssessmentTemplate;
use App\Models\ClinicalPathway;
use Database\Seeders\AssessmentTemplateSeeder;
use Database\Seeders\ClinicalPathwaySeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

/** PR 10 — additional specialty content packs seed cleanly. */
class CareContentPacksTest extends TestCase
{
    use RefreshDatabase;

    public function test_all_core_assessment_packs_seed(): void
    {
        $this->seed(AssessmentTemplateSeeder::class);

        $expected = [
            'universal_intake',
            'nihss',
            'mrs',
            'barthel',
            'gcs',
            'stroke_swallow',
            'stroke_clinical',
            'diabetes_core',
            'outcome_core',
            'heart_failure_core',
            'ckd_core',
            'hypertension_core',
            'asthma_core',
            'copd_core',
            'dementia_core',
            'parkinsons_core',
            'cancer_core',
            'pregnancy_core',
            'orthopaedics_core',
        ];

        foreach ($expected as $code) {
            $this->assertNotNull(
                AssessmentTemplate::currentSystemByCode($code),
                "Missing template {$code}"
            );
        }
    }

    public function test_all_pathways_seed_with_required_bindings(): void
    {
        $this->seed(AssessmentTemplateSeeder::class);
        $this->seed(ClinicalPathwaySeeder::class);

        $expected = [
            'stroke',
            'diabetes',
            'heart_failure',
            'ckd',
            'hypertension',
            'asthma',
            'copd',
            'dementia',
            'parkinsons',
            'cancer',
            'pregnancy',
            'orthopaedics',
        ];

        foreach ($expected as $code) {
            $pathway = ClinicalPathway::findByCode($code);
            $this->assertNotNull($pathway, "Missing pathway {$code}");
            $this->assertGreaterThanOrEqual(
                1,
                $pathway->templates()->where('is_required_on_activation', true)->count(),
                "Pathway {$code} needs a required template"
            );
        }
    }

    public function test_copd_and_heart_failure_scoring_templates(): void
    {
        $this->seed(AssessmentTemplateSeeder::class);

        $copd = AssessmentTemplate::currentSystemByCode('copd_core');
        $hf = AssessmentTemplate::currentSystemByCode('heart_failure_core');

        $this->assertSame('single_value', $copd->scoring_strategy);
        $this->assertSame('single_value', $hf->scoring_strategy);
        $this->assertTrue($copd->questions()->where('code', 'mmrc')->exists());
        $this->assertTrue($hf->questions()->where('code', 'nyha')->exists());
    }

    public function test_reseed_preserves_questions_that_have_answers(): void
    {
        $this->seed(AssessmentTemplateSeeder::class);

        $user = \App\Models\User::create([
            'public_id' => 'pack-reseed-user',
            'name' => 'Pack',
            'email' => 'pack-reseed@example.com',
        ]);
        $organization = \App\Models\Organization::create([
            'owner_ref' => $user->public_id,
            'name' => 'Pack Clinic',
            'slug' => 'pack-clinic',
            'settings' => ['onboarded' => true],
        ]);
        $branch = \App\Models\Branch::create([
            'owner_ref' => $user->public_id,
            'organization_id' => $organization->id,
            'name' => 'Main',
            'is_active' => true,
        ]);

        $template = AssessmentTemplate::currentSystemByCode('universal_intake');
        $this->assertNotNull($template);
        $question = $template->questions()->orderBy('id')->first();
        $this->assertNotNull($question);
        $questionId = $question->id;

        $patient = \App\Models\Patient::create([
            'owner_ref' => $user->public_id,
            'organization_id' => $organization->id,
            'branch_id' => $branch->id,
            'patient_number' => 'P-PACK-1',
            'first_name' => 'Pack',
            'last_name' => 'Patient',
        ]);

        $assessment = \App\Models\Assessment::create([
            'owner_ref' => $user->public_id,
            'organization_id' => $organization->id,
            'branch_id' => $branch->id,
            'patient_id' => $patient->id,
            'template_id' => $template->id,
            'status' => \App\Models\Assessment::STATUS_DRAFT,
            'assessed_at' => now(),
        ]);

        \App\Models\AssessmentAnswer::create([
            'owner_ref' => $user->public_id,
            'assessment_id' => $assessment->id,
            'question_id' => $questionId,
            'value_text' => 'kept',
        ]);

        // Delete nursing packs so ensureAssessmentCatalog re-runs the seeder.
        AssessmentTemplate::query()
            ->whereNull('organization_id')
            ->whereIn('code', ['news2', 'braden', 'morse', 'pain_nrs'])
            ->delete();

        app(\App\Services\Care\CareFeatures::class)->ensureAssessmentCatalog();

        $this->assertDatabaseHas('care_assessment_questions', ['id' => $questionId]);
        $this->assertDatabaseHas('care_assessment_answers', [
            'assessment_id' => $assessment->id,
            'question_id' => $questionId,
            'value_text' => 'kept',
        ]);
        $this->assertNotNull(AssessmentTemplate::currentSystemByCode('news2'));
    }
}
