<?php

namespace App\Http\Controllers;

use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class TenantOnboardingController extends Controller
{
    public function __invoke(Request $request): RedirectResponse
    {
        $clientId = config('graph.client_id');
        $redirectUri = route('admin.consent.callback');
        $targetTenant = $request->string('tenant')->toString() ?: config('graph.tenant_id', 'organizations');
        $tenantSegment = $targetTenant ?: 'organizations';

        abort_if(empty($clientId) || empty($redirectUri), 500, 'Graph client not configured');

        $state = Str::uuid()->toString();
        $request->session()->put('tenant_onboard_state', $state);

        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId($request);

        if ($workspaceId !== null) {
            $request->session()->put('tenant_onboard_workspace_id', (int) $workspaceId);
        }

        $url = "https://login.microsoftonline.com/{$tenantSegment}/v2.0/adminconsent?".http_build_query([
            'client_id' => $clientId,
            'redirect_uri' => $redirectUri,
            'scope' => 'https://graph.microsoft.com/.default',
            'state' => $state,
        ]);

        return redirect()->away($url);
    }
}
