<?php

namespace App\Console\Commands;

use App\Models\MexcoOrganisation;
use App\Models\MeetupEvent;
use App\Services\OrganisationService;
use Illuminate\Console\Command;
use Illuminate\Support\Str;

class MexcoBackfillOrganisations extends Command
{
    protected $signature = 'mexco:backfill-organisations';

    protected $description = 'Create default organisation, link events, and migrate legacy organiser accounts';

    public function handle(OrganisationService $organisations): int
    {
        $default = MexcoOrganisation::query()->firstOrCreate(
            ['slug' => 'unassigned'],
            [
                'name' => 'Unassigned',
                'type' => 'other',
                'status' => 'active',
            ]
        );

        $umpsa = MexcoOrganisation::query()->firstOrCreate(
            ['slug' => 'umpsa'],
            [
                'name' => 'UMPSA',
                'type' => 'university',
                'contact_person' => 'Demo Contact',
                'email' => 'events@umpsa.edu.my',
                'status' => 'active',
            ]
        );

        $linked = 0;
        $migrated = 0;

        foreach (MeetupEvent::query()->orderBy('id')->get() as $event) {
            if (! $event->organisation_id) {
                $orgId = str_contains(strtolower($event->id.$event->name), 'icaiia') ? $umpsa->id : $default->id;
                $event->update(['organisation_id' => $orgId]);
                $linked++;
            }

            if ($organisations->migrateLegacyOrganiser($event->fresh())) {
                $migrated++;
            }
        }

        $this->info("Done. Events linked: {$linked}. Organisers migrated: {$migrated}.");

        return self::SUCCESS;
    }
}
