<?php

declare(strict_types=1);

namespace SHServ\Integrations\GAuth\Webhook\Handlers;

use GNexus\GAuth\DTO\WebhookEvent;

final class UserHandler
{
    public function handle(WebhookEvent $event): void
    {
        $data = $event->metadata;
        $user = $data['user'] ?? [];
        $gauthUserId = $user['id'] ?? null;
        if (!$gauthUserId) {
            return;
        }

        $tb = app()->thin_builder;

        switch ($event->eventType) {
            case 'user.updated':
                $tb->update('shserv_users', [
                    'email' => $user['email'] ?? null,
                    'display_name' => $user['display_name'] ?? null,
                    'status' => $user['status'] ?? 'active',
                ], [['gauth_user_id', '=', $gauthUserId]]);
                break;

            case 'user.blocked':
                $tb->update('shserv_users', ['status' => 'blocked'], [['gauth_user_id', '=', $gauthUserId]]);
                // Clear sessions
                $localUser = $tb->select('shserv_users', ['id'], [['gauth_user_id', '=', $gauthUserId]]);
                if ($localUser) {
                    $tb->delete('shserv_sessions', [['user_id', '=', $localUser[0]['id']]]);
                }
                break;

            case 'user.unblocked':
                $tb->update('shserv_users', ['status' => 'active'], [['gauth_user_id', '=', $gauthUserId]]);
                break;

            case 'user.deleted':
                $tb->delete('shserv_users', [['gauth_user_id', '=', $gauthUserId]]);
                break;
        }
    }
}
