<?php

declare(strict_types=1);

namespace SHServ\Integrations\GAuth\Webhook\Handlers;

use GNexus\GAuth\DTO\WebhookEvent;

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

        if (!$gauthUserId || !$gauthGroupId) {
            return;
        }

        $tb = app()->thin_builder;

        $localUser = $tb->select('shserv_users', ['id'], [['gauth_user_id', '=', $gauthUserId]]);
        $localGroup = $tb->select('shserv_groups', ['id'], [['gauth_group_id', '=', $gauthGroupId]]);

        if (!$localUser || !$localGroup) {
            return;
        }

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

        switch ($event->eventType) {
            case 'group.user_added':
                $tb->query("
                    INSERT IGNORE INTO shserv_group_members (group_id, user_id)
                    VALUES ({$groupId}, {$userId})
                ");
                break;

            case 'group.user_removed':
                $tb->query("
                    DELETE FROM shserv_group_members
                    WHERE group_id = {$groupId} AND user_id = {$userId}
                ");
                break;
        }
    }
}
