<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class MatrixRegistrationService
{
    public function registerUser(string $username, string $password)
    {
        $server = config('services.matrix.server');
        $secret = config('services.matrix.shared_secret');

        // Get nonce from Synapse
        $nonceResponse = Http::get("$server/_synapse/admin/v1/register");

        if (! $nonceResponse->ok()) {
            throw new \Exception('Could not fetch nonce from Matrix.');
        }

        $nonce = $nonceResponse->json()['nonce'];

        // Generate MAC
        $mac = hash_hmac(
            'sha1',
            $nonce."\0".
            $username."\0".
            $password."\0".
            'notadmin',
            $secret
        );

        // Send registration request
        $response = Http::post("$server/_synapse/admin/v1/register", [
            'nonce' => $nonce,
            'username' => $username,
            'password' => $password,
            'admin' => false,
            'mac' => $mac,
        ]);

        if ($response->failed()) {
            $error = $response->json()['error'] ?? $response->body();
            throw new \Exception($error);
        }

        return $response->json();
    }
}
