<?php

namespace Tests\Feature\Mexco;

use App\Models\MexcoEventLicense;
use App\Models\MexcoOrganisationUser;
use App\Models\MeetupEvent;
use App\Models\MeetupParticipant;
use App\Services\EntitlementService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\Concerns\SetsUpMexcoPlatform;
use Tests\TestCase;

class DemoTrialTest extends TestCase
{
    use RefreshDatabase;
    use SetsUpMexcoPlatform;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seedMexcoPlatform();
    }

    public function test_guest_can_view_demo_page_with_default_accounts(): void
    {
        $this->get(route('mexco.demo'))
            ->assertOk()
            ->assertSee('Try MeXCo with default demo accounts')
            ->assertSee('organiser@demo.mexco')
            ->assertSee('visitor@demo.mexco')
            ->assertSee('900101123456')
            ->assertSee('Open Organizer')
            ->assertSee('Open Visitor Pass');

        $this->assertDatabaseHas('meetup_events', [
            'id' => 'mexcodemo',
            'organiser_username' => 'organiser@demo.mexco',
        ]);

        $this->assertTrue(
            MeetupParticipant::query()
                ->where('event_id', 'mexcodemo')
                ->where('email', 'visitor@demo.mexco')
                ->exists()
        );
    }

    public function test_registering_for_demo_uses_default_password_and_participants(): void
    {
        $this->post(route('mexco.register.submit'), [
            'name' => 'Demo User',
            'email' => 'demo.user@example.com',
            'password' => 'password123',
            'password_confirmation' => 'password123',
            'organisation_name' => 'Demo Org',
            'organisation_type' => 'corporate',
            'plan' => 'demo',
        ])->assertRedirect(route('mexco.portal.dashboard'));

        $user = MexcoOrganisationUser::query()->where('email', 'demo.user@example.com')->firstOrFail();
        $license = MexcoEventLicense::query()
            ->where('is_trial', true)
            ->whereHas('event', fn ($q) => $q->where('organisation_id', $user->organisation_id))
            ->with(['event', 'plan'])
            ->firstOrFail();

        $this->assertSame('demo', $license->plan->code);
        $this->assertSame('active', $license->status);
        $this->assertTrue($license->event->verifyOrganiserPassword('1234'));
        $this->assertTrue(
            MeetupParticipant::query()
                ->where('event_id', $license->event_id)
                ->where('email', 'visitor@demo.mexco')
                ->exists()
        );

        $entitlements = app(EntitlementService::class);
        $this->assertTrue($entitlements->allows($license->event_id, 'booth_voting'));
        $this->assertTrue($entitlements->allows($license->event_id, 'floor_plan'));
    }
}
