<?php

namespace App\Services;

use App\User;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;

class DiscordService
{
    /**
     * Sends a token revocation request to Discord to invalidate a specific $user's tokens.
     * Please ensure you have the user set a password for their account after this, or request new tokens.
     *
     * @see https://www.rfc-editor.org/rfc/rfc7009
     *
     * @param  User  $user
     * @return bool
     *
     * @throws RequestException
     */
    public function revokeAccountTokens(User $user): bool
    {
        $req = Http::asForm()->post(config('services.discord.base_url').'/oauth2/token/revoke', [
            'client_id' => config('services.discord.client_id'),
            'client_secret' => config('services.discord.client_secret'),
            'token' => $user->discord_token,
        ])->throw();

        $user->discord_token = null;
        $user->discord_user_id = null;
        $user->discord_refresh_token = null;
        $user->discord_pfp = null;
        $user->save();

        return $req->ok();
    }
}
