<?php

declare(strict_types=1);

namespace SHServ\Integrations\GAuth\Webhook\Handlers;

use GNexus\GAuth\DTO\WebhookEvent;
use SHServ\Integrations\GAuth\UserResolver;

final class RoleHandler
{
    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', 'system_role'], [['gauth_user_id', '=', $gauthUserId]]);
        if (!$localUser) {
            return;
        }

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

        switch ($event->eventType) {
            case 'client.roles_changed':
                $roles = $data['roles'] ?? [];
                // Update system_role if it changed
                $clientId = FCONF['gauth']['client_id'] ?? '';
                // In first version, roles array contains strings
                if (!empty($roles)) {
                    $systemRole = in_array('superadmin', $roles, true) ? 'superadmin'
                        : (in_array('admin', $roles, true) ? 'admin' : 'user');
                    $tb->update('shserv_users', ['system_role' => $systemRole], [['id', '=', $userId]]);
                }
                break;

            case 'client.permissions_changed':
                // Full re-sync of permissions for this user
                // We need to re-fetch from gnexus-auth, but webhook gives us changed_permissions
                $changed = $data['changed_permissions'] ?? [];
                foreach ($changed as $permSlug) {
                    // Remove old auto-synced record and re-insert
                    $tb->query("
                        DELETE FROM shserv_user_permissions
                        WHERE user_id = {$userId} AND permission_slug = '{$permSlug}' AND set_by_user_id IS NULL
                    ");
                }
                break;
        }
    }
}
