<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Assessment;
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\User;
use App\Models\Visit;
use App\Services\Care\CareFeatures;
use Database\Seeders\AssessmentTemplateSeeder;
use Database\Seeders\ClinicalPathwaySeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class CareAssessmentApiTest 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' => 'api-assess-user',
            'name' => 'API User',
            'email' => 'api-assess@example.com',
        ]);

        $this->organization = Organization::create([
            'owner_ref' => $this->user->public_id,
            'name' => 'API Clinic',
            'slug' => 'api-clinic',
            'timezone' => 'UTC',
            'settings' => [
                'onboarded' => true,
                'plan' => 'pro',
                'plan_expires_at' => now()->addMonth()->toIso8601String(),
                '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-API-001',
            'first_name' => 'Ama',
            'last_name' => 'Api',
        ]);

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

        Sanctum::actingAs($this->user);
    }

    public function test_api_lists_templates_and_404_when_flag_off(): void
    {
        // Engine defaults ON when rollout flag is unset.
        $this->getJson('/api/v1/assessment-templates')
            ->assertOk()
            ->assertJsonPath('data.0.code', fn ($c) => is_string($c));

        $this->organization->update([
            'settings' => array_merge($this->organization->settings ?? [], [
                'rollout' => [CareFeatures::ASSESSMENTS_ENGINE => false],
            ]),
        ]);
        $this->organization->refresh();

        $this->getJson('/api/v1/assessment-templates')->assertNotFound();
    }

    public function test_api_assessment_lifecycle_with_uuids(): void
    {
        $create = $this->postJson("/api/v1/patients/{$this->patient->uuid}/assessments", [
            'template_code' => 'mrs',
        ])->assertSuccessful();

        $uuid = $create->json('uuid');
        $this->assertNotEmpty($uuid);

        $updated = $this->putJson("/api/v1/assessments/{$uuid}", [
            'answers' => ['mrs_score' => '3'],
        ])->assertOk();

        $this->assertEquals(3, (float) $updated->json('answers.mrs_score'));

        $completed = $this->postJson("/api/v1/assessments/{$uuid}/complete")
            ->assertOk()
            ->assertJsonPath('status', 'completed');

        $this->assertEquals(3, (float) $completed->json('score.total_score'));

        $this->putJson("/api/v1/assessments/{$uuid}", [
            'answers' => ['mrs_score' => '4'],
        ])->assertStatus(422);
    }

    public function test_api_pathway_suggestions_and_activate(): 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' => 'I63.9',
            'description' => 'Cerebral infarction',
            'is_primary' => true,
        ]);

        $this->getJson("/api/v1/consultations/{$consultation->uuid}/pathway-suggestions")
            ->assertOk()
            ->assertJsonPath('data.0.pathway_code', 'stroke');

        $this->postJson("/api/v1/patients/{$this->patient->uuid}/pathways", [
            'pathway_code' => 'stroke',
            'consultation_uuid' => $consultation->uuid,
        ])
            ->assertCreated()
            ->assertJsonPath('pathway_code', 'stroke')
            ->assertJsonPath('status', 'active');

        $this->getJson("/api/v1/patients/{$this->patient->uuid}/pathways")
            ->assertOk()
            ->assertJsonPath('active.0.pathway_code', 'stroke');

        $this->assertGreaterThanOrEqual(2, Assessment::where('status', Assessment::STATUS_DRAFT)->count());
    }

    public function test_api_tenant_isolation(): void
    {
        $other = User::create([
            'public_id' => 'other-api',
            'name' => 'Other',
            'email' => 'other-api@example.com',
        ]);
        $otherOrg = Organization::create([
            'owner_ref' => $other->public_id,
            'name' => 'Other',
            'slug' => 'other-api',
            'timezone' => 'UTC',
            'settings' => [
                'onboarded' => true,
                'rollout' => [CareFeatures::ASSESSMENTS_ENGINE => true],
            ],
        ]);
        Member::create([
            'owner_ref' => $other->public_id,
            'organization_id' => $otherOrg->id,
            'user_ref' => $other->public_id,
            'role' => 'doctor',
        ]);
        $otherPatient = Patient::create([
            'uuid' => (string) Str::uuid(),
            'owner_ref' => $other->public_id,
            'organization_id' => $otherOrg->id,
            'patient_number' => 'LC-OTHER',
            'first_name' => 'X',
            'last_name' => 'Y',
        ]);

        $this->getJson("/api/v1/patients/{$otherPatient->uuid}/assessments")->assertNotFound();
    }

    public function test_api_catalog_includes_pr10_pathways(): void
    {
        $this->getJson('/api/v1/pathways')
            ->assertOk()
            ->assertJsonFragment(['code' => 'copd'])
            ->assertJsonFragment(['code' => 'heart_failure'])
            ->assertJsonFragment(['code' => 'dementia']);

        $this->assertNotNull(ClinicalPathway::findByCode('pregnancy'));
        $this->assertNotNull(ClinicalPathway::findByCode('orthopaedics'));
    }
}
