<?php

namespace Tests\Feature;

use App\Http\Middleware\EnsurePlatformSession;
use App\Models\User;
use App\Services\Care\DemoLoginReseeder;
use App\Services\Care\DemoTenantSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;

class DemoLoginReseederTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->withoutMiddleware(EnsurePlatformSession::class);
        config([
            'demo_accounts.enabled' => true,
            'demo_accounts.reset_on_login' => true,
        ]);
        Cache::flush();
    }

    public function test_it_reseeds_demo_free_user_after_login(): void
    {
        $user = User::create([
            'public_id' => 'demo-free-pid',
            'name' => 'Ladill Demo (Free)',
            'email' => 'demo-free@ladill.com',
        ]);

        $seeder = $this->mock(DemoTenantSeeder::class);
        $seeder->shouldReceive('ensureOnboardedShell')
            ->once()
            ->withArgs(fn (User $u, string $plan) => $u->is($user) && $plan === 'free')
            ->andReturn(new \App\Models\Organization);
        $seeder->shouldReceive('seed')
            ->once()
            ->withArgs(fn (User $u, string $plan, bool $reset) => $u->is($user) && $plan === 'free' && $reset === true)
            ->andReturn(['ok' => true]);

        app(DemoLoginReseeder::class)->maybeResetAfterLogin($user);

        $this->app->terminate();
    }

    public function test_it_skips_non_demo_users(): void
    {
        $user = User::create([
            'public_id' => 'regular-pid',
            'name' => 'Regular',
            'email' => 'regular@example.com',
        ]);

        $seeder = $this->mock(DemoTenantSeeder::class);
        $seeder->shouldReceive('ensureOnboardedShell')->never();
        $seeder->shouldReceive('seed')->never();

        app(DemoLoginReseeder::class)->maybeResetAfterLogin($user);
        $this->app->terminate();
    }

    public function test_it_skips_when_disabled(): void
    {
        config(['demo_accounts.enabled' => false]);

        $user = User::create([
            'public_id' => 'demo-free-pid',
            'name' => 'Ladill Demo (Free)',
            'email' => 'demo-free@ladill.com',
        ]);

        $seeder = $this->mock(DemoTenantSeeder::class);
        $seeder->shouldReceive('ensureOnboardedShell')->never();
        $seeder->shouldReceive('seed')->never();

        app(DemoLoginReseeder::class)->maybeResetAfterLogin($user);
        $this->app->terminate();
    }

    public function test_it_skips_staff_demo_logins(): void
    {
        $user = User::create([
            'public_id' => 'demo-pro-doctor-pid',
            'name' => 'Dr. Kwame Mensah (Pro)',
            'email' => 'demo-pro-doctor@ladill.com',
        ]);

        $seeder = $this->mock(DemoTenantSeeder::class);
        $seeder->shouldReceive('ensureOnboardedShell')->never();
        $seeder->shouldReceive('seed')->never();

        app(DemoLoginReseeder::class)->maybeResetAfterLogin($user);
        $this->app->terminate();
    }

    public function test_login_shell_is_onboarded_before_async_reseed(): void
    {
        $user = User::create([
            'public_id' => 'demo-shell-pid',
            'name' => 'Ladill Demo (Pro)',
            'email' => 'demo-pro@ladill.com',
        ]);

        app(DemoLoginReseeder::class)->maybeResetAfterLogin($user);

        $this->assertTrue(app(\App\Services\Care\OrganizationResolver::class)->isOnboarded($user));
    }

    public function test_empty_demo_tenant_seeds_synchronously(): void
    {
        $user = User::create([
            'public_id' => 'demo-empty-pid',
            'name' => 'Ladill Demo (Pro)',
            'email' => 'demo-pro@ladill.com',
        ]);

        $org = \App\Models\Organization::create([
            'owner_ref' => $user->public_id,
            'name' => 'Empty Shell',
            'slug' => 'empty-shell',
            'timezone' => 'UTC',
            'settings' => [
                'onboarded' => true,
                'rollout' => ['workflow_engine' => true],
            ],
        ]);

        app(DemoLoginReseeder::class)->maybeResetAfterLogin($user);

        $org->refresh();
        $this->assertTrue((bool) data_get($org->settings, 'demo'));
        $this->assertFalse((bool) data_get($org->settings, 'rollout.workflow_engine'));
        $this->assertGreaterThan(0, \App\Models\Patient::query()->where('organization_id', $org->id)->count());
    }
}
