<?php

declare(strict_types=1);

namespace App\ApiClient;

use App\ApiClient\DTOs\UserDto;

/**
 * Wraps the api's `/api/v1/auth/*` endpoints. These exist *exclusively*
 * for the UI BFF; they're called with the service token but with no
 * `X-Acting-User-Id` header (would be circular — the endpoints exist to
 * resolve the user record we'd impersonate).
 */
final class AuthClient
{
    public function __construct(private readonly ApiClient $api)
    {
    }

    /**
     * @param list<string> $groups Entra group object IDs from the ID token's `groups` claim.
     */
    public function upsertOidc(string $subject, ?string $email, string $displayName, array $groups): UserDto
    {
        $payload = $this->api->request(
            'POST',
            '/api/v1/auth/users/upsert-oidc',
            [
                'json' => [
                    'subject' => $subject,
                    'email' => $email,
                    'display_name' => $displayName,
                    'groups' => array_values($groups),
                ],
            ],
        );

        return UserDto::fromArray($payload);
    }

    public function upsertLocal(string $username): UserDto
    {
        $payload = $this->api->request(
            'POST',
            '/api/v1/auth/users/upsert-local',
            ['json' => ['username' => $username]],
        );

        return UserDto::fromArray($payload);
    }
}
