<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Assessment;
use App\Models\Branch;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\User;
use App\Services\Care\CareFeatures;
use App\Services\Care\FhirAssessmentExporter;
use Database\Seeders\AssessmentTemplateSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class CareAssessmentExtrasTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

    protected Organization $organization;

    protected Patient $patient;

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

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

        $this->organization = Organization::create([
            'owner_ref' => $this->user->public_id,
            'name' => 'Extras Clinic',
            'slug' => 'extras-clinic',
            'timezone' => 'UTC',
            'settings' => [
                'onboarded' => true,
                'plan' => 'enterprise',
                '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',
        ]);

        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,
            'patient_number' => 'LC-EX-001',
            'first_name' => 'Extra',
            'last_name' => 'Patient',
        ]);

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

    public function test_enterprise_assessment_analytics_report(): void
    {
        $this->actingAs($this->user)
            ->post(route('care.assessments.store', $this->patient), ['template_code' => 'mrs'])
            ->assertRedirect();

        $assessment = Assessment::first();
        $this->actingAs($this->user)
            ->put(route('care.assessments.update', $assessment), ['answers' => ['mrs_score' => '2']]);
        $this->actingAs($this->user)
            ->post(route('care.assessments.complete', $assessment));

        $this->actingAs($this->user)
            ->get(route('care.reports.show', ['type' => 'assessments']))
            ->assertOk()
            ->assertSee('Assessment analytics')
            ->assertSee('By clinical form')
            ->assertSee('mrs');
    }

    public function test_pro_plan_blocked_from_assessment_analytics_without_feature(): void
    {
        // Pro can access paid reports middleware, but lacks assessment_analytics (Enterprise-only).
        $this->organization->update([
            'settings' => [
                'onboarded' => true,
                'plan' => 'pro',
                'plan_expires_at' => now()->addMonth()->toIso8601String(),
                'rollout' => [CareFeatures::ASSESSMENTS_ENGINE => true],
            ],
        ]);

        $this->actingAs($this->user)
            ->get(route('care.reports.show', ['type' => 'assessments']))
            ->assertForbidden();
    }

    public function test_fhir_export_web_and_api(): void
    {
        $this->actingAs($this->user)
            ->post(route('care.assessments.store', $this->patient), ['template_code' => 'mrs'])
            ->assertRedirect();

        $assessment = Assessment::first();
        $this->actingAs($this->user)
            ->put(route('care.assessments.update', $assessment), ['answers' => ['mrs_score' => '1']]);
        $this->actingAs($this->user)
            ->post(route('care.assessments.complete', $assessment));

        $bundle = app(FhirAssessmentExporter::class)->exportBundle($assessment->fresh(['template.questions', 'answers.question', 'patient', 'score']));
        $this->assertSame('Bundle', $bundle['resourceType']);
        $this->assertSame('Questionnaire', $bundle['entry'][0]['resource']['resourceType']);
        $this->assertSame('QuestionnaireResponse', $bundle['entry'][1]['resource']['resourceType']);
        $this->assertSame('completed', $bundle['entry'][1]['resource']['status']);

        $this->actingAs($this->user)
            ->get(route('care.assessments.fhir', $assessment).'?download=1')
            ->assertOk();

        Sanctum::actingAs($this->user);
        $this->getJson('/api/v1/assessments/'.$assessment->uuid.'/fhir')
            ->assertOk()
            ->assertJsonPath('resourceType', 'Bundle')
            ->assertJsonPath('entry.1.resource.resourceType', 'QuestionnaireResponse');
    }
}
