<?php

namespace App\Listeners;

use App\Events\ServiceEventOccurred;
use App\Models\Member;
use App\Models\Organization;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * Reacts to platform lifecycle events pushed from the Ladill monolith.
 */
class PlatformServiceEventListener
{
    public function handle(ServiceEventOccurred $event): void
    {
        match ($event->name) {
            'user.deleted' => $this->handleUserDeleted($event),
            'user.suspended' => $this->handleUserSuspended($event),
            'organization.updated' => $this->handleOrganizationUpdated($event),
            default => null,
        };
    }

    protected function handleUserDeleted(ServiceEventOccurred $event): void
    {
        $publicId = (string) ($event->data['user'] ?? '');
        if ($publicId === '') {
            return;
        }

        DB::transaction(function () use ($publicId) {
            Member::where('user_ref', $publicId)->delete();
            User::where('public_id', $publicId)->delete();
        });

        Log::info('PlatformServiceEventListener: user deleted', ['public_id' => $publicId]);
    }

    protected function handleUserSuspended(ServiceEventOccurred $event): void
    {
        $publicId = (string) ($event->data['user'] ?? '');
        if ($publicId === '') {
            return;
        }

        $user = User::where('public_id', $publicId)->first();
        if ($user) {
            $user->tokens()->delete();
        }

        Log::info('PlatformServiceEventListener: user suspended', ['public_id' => $publicId]);
    }

    protected function handleOrganizationUpdated(ServiceEventOccurred $event): void
    {
        $ownerRef = (string) ($event->data['owner'] ?? $event->data['user'] ?? '');
        if ($ownerRef === '') {
            return;
        }

        $organization = Organization::owned($ownerRef)->first();
        if (! $organization) {
            return;
        }

        $updates = array_filter([
            'name' => $event->data['name'] ?? null,
            'timezone' => $event->data['timezone'] ?? null,
        ], fn ($value) => $value !== null && $value !== '');

        if ($updates === []) {
            return;
        }

        $organization->update($updates);

        Log::info('PlatformServiceEventListener: organization updated', [
            'organization_id' => $organization->id,
            'owner_ref' => $ownerRef,
        ]);
    }
}
