<?php

namespace Velis\Mail\Protocol;

use Velis\Microsoft\TokenService;

class XOauth2Auth
{
    public const AUTH_METHOD = 'xoauth2';

    private TokenService $tokenService;

    public function __construct(TokenService $tokenService)
    {
        $this->tokenService = $tokenService;
    }

    protected function getAuthToken(string $clientId, string $clientSecret): string
    {
        return $this->tokenService->getToken(
            $clientId,
            $clientSecret,
            'https://outlook.office365.com/.default'
        );
    }

    /**
     * encodes accessToken and target mailbox to Xoauth2 SASL base64 encoded string
     */
    public function encodeXoauth2Sasl(string $username, string $clientId, string $clientSecret): string
    {
        return base64_encode(
            sprintf(
                "user=%s%sauth=Bearer %s%s%s",
                $username,
                chr(0x01),
                $this->getAuthToken($clientId, $clientSecret),
                chr(0x01),
                chr(0x01)
            )
        );
    }
}
