<?php

namespace Tests\Concerns;

use App\Models\MeetupSuperAdmin;
use App\Models\MexcoOrganisation;
use App\Services\BillingService;
use App\Services\CampusService;
use App\Services\EntitlementService;
use App\Services\MeetupService;
use Database\Seeders\MexcoCatalogSeeder;
use Database\Seeders\MexcoNotificationTemplateSeeder;
use Database\Seeders\MexcoPlatformSettingsSeeder;

trait SetsUpMexcoPlatform
{
    protected function seedMexcoPlatform(): void
    {
        $this->seed([
            MexcoCatalogSeeder::class,
            MexcoPlatformSettingsSeeder::class,
            MexcoNotificationTemplateSeeder::class,
        ]);
    }

    protected function createSuperAdmin(string $email = 'admin@test.mexco'): MeetupSuperAdmin
    {
        return MeetupSuperAdmin::query()->create([
            'name' => 'Test Super Admin',
            'email' => $email,
            'password' => 'password123',
            'status' => 'active',
        ]);
    }

    protected function actingAsSuperAdmin(?MeetupSuperAdmin $admin = null): static
    {
        $admin ??= $this->createSuperAdmin();

        return $this->withSession([
            'meetup_super_authenticated' => true,
            'meetup_super_admin_id' => $admin->id,
            'meetup_super_admin_name' => $admin->name,
        ]);
    }

    protected function createOrganisation(string $name = 'UMPSA', string $slug = 'umpsa'): MexcoOrganisation
    {
        return MexcoOrganisation::query()->create([
            'name' => $name,
            'slug' => $slug,
            'type' => 'university',
            'email' => 'contact@'.$slug.'.edu.my',
            'status' => 'active',
        ]);
    }

    protected function createLicensedEvent(
        MexcoOrganisation $organisation,
        string $eventId,
        string $name,
        string $planCode,
        array $overrides = [],
    ): \App\Models\MeetupEvent {
        $meetup = app(MeetupService::class);
        $entitlements = app(EntitlementService::class);
        $billing = app(BillingService::class);

        $event = $meetup->createEvent(array_merge([
            'id' => $eventId,
            'organisation_id' => $organisation->id,
            'name' => $name,
            'event_name' => $name,
            'organiser_username' => "organiser@{$eventId}.test",
            'organiser_password' => '1234',
            'starts_at' => now()->addMonth(),
            'ends_at' => now()->addMonth()->addDays(2),
        ], $overrides));

        $license = $entitlements->assignPlan($event->id, $planCode);

        if ($planCode === 'campus') {
            $license->update([
                'is_campus_sponsored' => true,
                'price_cents' => 0,
                'sponsorship_value_cents' => 99900,
            ]);
            $entitlements->rebuildEntitlements($event->id);
        }

        $billing->createDraftInvoiceForLicense($event->fresh(), $license->fresh());

        return $event->fresh(['license.plan']);
    }
}
