<?php

declare(strict_types=1);

namespace SHServ\Integrations\GAuth\Webhook\Handlers;

use GNexus\GAuth\DTO\WebhookEvent;

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

        if (!$gauthUserId) {
            return;
        }

        $tb = app()->thin_builder;
        $localUser = $tb->select('shserv_users', ['id'], [['gauth_user_id', '=', $gauthUserId]]);
        if (!$localUser) {
            return;
        }

        $userId = (int) $localUser[0]['id'];

        switch ($event->eventType) {
            case 'auth.global_logout':
                $tb->delete('shserv_sessions', [['user_id', '=', $userId]]);
                break;

            case 'session.revoked':
                $sessionId = $data['session_id'] ?? null;
                if ($sessionId) {
                    $tb->query("
                        DELETE FROM shserv_sessions
                        WHERE user_id = {$userId} AND session_token = '{$sessionId}'
                    ");
                }
                break;
        }
    }
}
