<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Branch;
use App\Models\Member;
use App\Models\Organization;
use App\Models\User;
use App\Services\Care\SpecialtyModuleService;
use App\Services\Care\SpecialtyShellService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CareWomensHealthAccessTest extends TestCase
{
    use RefreshDatabase;

    protected User $owner;

    protected Organization $organization;

    protected SpecialtyModuleService $modules;

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

        $this->owner = User::create([
            'public_id' => 'wh-access-owner',
            'name' => 'Owner',
            'email' => 'wh-access-owner@example.com',
        ]);

        $this->organization = Organization::create([
            'owner_ref' => $this->owner->public_id,
            'name' => 'WH Clinic',
            'slug' => 'wh-access-clinic',
            'settings' => [
                'onboarded' => true,
                'plan' => 'pro',
                'plan_expires_at' => now()->addMonth()->toIso8601String(),
            ],
        ]);

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

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

        $this->modules = app(SpecialtyModuleService::class);
        $this->modules->activate($this->organization, $this->owner->public_id, 'womens_health');
        $this->modules->activate($this->organization->fresh(), $this->owner->public_id, 'fertility');
        $this->organization->refresh();
    }

    protected function makeStaff(string $role, string $suffix): Member
    {
        $user = User::create([
            'public_id' => 'wh-'.$suffix,
            'name' => $role,
            'email' => $suffix.'@example.com',
        ]);

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

    public function test_obgyn_roles_manage_womens_health(): void
    {
        foreach (['obstetrician', 'gynecologist', 'obgyn', 'midwife', 'labour_ward_nurse'] as $role) {
            $member = $this->makeStaff($role, $role.'1');
            $this->assertTrue(
                $this->modules->memberCanManage($this->organization, $member, 'womens_health'),
                "{$role} should manage womens_health",
            );
            $this->assertFalse(
                $this->modules->memberCanManage($this->organization, $member, 'fertility'),
                "{$role} should not manage fertility",
            );
        }
    }

    public function test_fertility_roles_manage_fertility_only(): void
    {
        foreach (['fertility_specialist', 'embryologist', 'fertility_nurse'] as $role) {
            $member = $this->makeStaff($role, $role.'1');
            $this->assertTrue($this->modules->memberCanManage($this->organization, $member, 'fertility'));
            $this->assertFalse($this->modules->memberCanManage($this->organization, $member, 'womens_health'));
        }
    }

    public function test_maternity_settings_migrate_to_womens_health(): void
    {
        $org = Organization::create([
            'owner_ref' => $this->owner->public_id,
            'name' => 'Legacy Mat',
            'slug' => 'legacy-mat',
            'settings' => [
                'onboarded' => true,
                'plan' => 'pro',
                'plan_expires_at' => now()->addMonth()->toIso8601String(),
                'specialty_modules' => ['maternity' => true],
                'specialty_module_provisioning' => [
                    'maternity' => ['active' => true, 'services' => [['code' => 'mat.anc', 'label' => 'ANC', 'amount_minor' => 100, 'type' => 'consultation']]],
                ],
            ],
        ]);

        $this->assertTrue($this->modules->isEnabled($org, 'womens_health'));
        $org->refresh();
        $this->assertTrue((bool) data_get($org->settings, 'specialty_modules.womens_health'));
        $this->assertFalse((bool) data_get($org->settings, 'specialty_modules.maternity'));
        $this->assertNotNull(data_get($org->settings, 'specialty_module_provisioning.womens_health'));
        $this->assertNull(data_get($org->settings, 'specialty_module_provisioning.maternity'));
        $this->assertSame('womens_health', $this->modules->normalizeKey('maternity'));
    }

    public function test_service_line_toggle_filters_catalog_services(): void
    {
        $shell = app(SpecialtyShellService::class);
        $before = collect($shell->catalogServices('womens_health', $this->organization))->pluck('code')->all();
        $this->assertContains('wh.gyn.consult', $before);

        $this->modules->syncServiceLines($this->organization, 'womens_health', [
            'gynecology' => false,
            'obstetrics' => true,
            'antenatal' => true,
            'labour_delivery' => true,
            'postnatal' => true,
            'family_planning' => false,
            'cervical_screening' => false,
            'menopause' => false,
            'high_risk_pregnancy' => false,
            'early_pregnancy' => false,
        ]);
        $this->organization->refresh();

        $after = collect($shell->catalogServices('womens_health', $this->organization->fresh()))->pluck('code')->all();
        $this->assertNotContains('wh.gyn.consult', $after);
        $this->assertContains('mat.anc', $after);
    }
}
