<?php

declare(strict_types=1);

if (!function_exists('myronRenderMcpOAuthErrorPage')) {
    function myronRenderMcpOAuthErrorPage(string $error, string $detail): void
    {
        http_response_code($error === 'access_denied' ? 403 : 400);
        header('Content-Type: text/html; charset=UTF-8');
        $user = myronCurrentUser();
        if (is_array($user)) {
            myronRenderAdminShellStart($user, [
                'title' => 'OAuth Request Error',
                'titleContext' => 'Administration',
                'activeItem' => 'ai-connections',
            ]);
            echo '<div class="mc-workspace__header"><span class="mc-workspace__eyebrow">OAuth</span><div class="mc-workspace__title-row"><h1 class="mc-workspace__title">Connector Request Failed</h1></div><p class="mc-workspace__subtitle">' . myronEscape($detail) . '</p></div><div class="mc-page-canvas mc-page-canvas--site"><section class="sg-section"><p><code>' . myronEscape($error) . '</code></p><a class="sg-button" href="' . myronEscape(myronBuildAdminUrl('administration.aiConnections')) . '">Return to AI Connections</a></section></div>';
            myronRenderAdminShellEnd();
            return;
        }

        echo '<!DOCTYPE html><html><body><h1>Connector Request Failed</h1><p>' . myronEscape($detail) . '</p><p><code>' . myronEscape($error) . '</code></p></body></html>';
    }
}

myronSendMcpOAuthNoStoreHeaders();

$currentUser = myronCurrentUser();
if (!is_array($currentUser)) {
    myronRedirect(myronBuildAdminUrl('auth.login') . '?next=' . rawurlencode((string) ($_SERVER['REQUEST_URI'] ?? '/oauth/authorize')));
}

$request = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;
$validation = myronMcpOAuthTokenService()->validateAuthorizationRequest($request);
if (($validation['ok'] ?? false) !== true) {
    myronRenderMcpOAuthErrorPage((string) ($validation['error'] ?? 'invalid_request'), (string) ($validation['detail'] ?? 'The authorization request is invalid.'));
    return;
}

$client = is_array($validation['client'] ?? null) ? $validation['client'] : [];
$scopes = array_values(array_map('strval', is_array($validation['scopes'] ?? null) ? $validation['scopes'] : []));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    myronRequireCsrf($_POST['csrf_token'] ?? null);
    if ((string) ($_POST['decision'] ?? '') !== 'approve') {
        myronRenderMcpOAuthErrorPage('access_denied', 'The connector request was denied.');
        return;
    }
    $code = myronMcpOAuthTokenService()->approveAuthorizationCode(
        (string) ($_POST['client_id'] ?? ''),
        (string) ($_POST['redirect_uri'] ?? ''),
        (string) ($_POST['resource'] ?? ''),
        $scopes,
        (string) ($_POST['code_challenge'] ?? ''),
        (string) ($_POST['code_challenge_method'] ?? ''),
        (string) ($currentUser['id'] ?? '')
    );
    $redirect = (string) ($_POST['redirect_uri'] ?? '');
    $separator = str_contains($redirect, '?') ? '&' : '?';
    $target = $redirect . $separator . 'code=' . rawurlencode($code);
    $state = (string) ($_POST['state'] ?? '');
    if ($state !== '') {
        $target .= '&state=' . rawurlencode($state);
    }
    myronRedirect($target);
}

$csrfToken = myronCsrfToken();
myronRenderAdminShellStart($currentUser, [
    'title' => 'Authorize MCP Connector',
    'titleContext' => 'Administration',
    'activeItem' => 'ai-connections',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Administration', 'href' => myronBuildAdminUrl('administration.aiConnections')],
      ['label' => 'Authorize MCP Connector'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Authorize MCP Connector</h1>
  </div>
  <p class="mc-workspace__subtitle">Approve this connector only if you initiated the request from a trusted MCP client.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <section class="sg-section">
    <h2 class="sg-section__title"><?= myronEscape((string) ($client['clientName'] ?? 'MCP Client')) ?></h2>
    <dl class="sg-define-list">
      <dt>Redirect URI</dt>
      <dd><code><?= myronEscape((string) ($_GET['redirect_uri'] ?? '')) ?></code></dd>
      <dt>Resource</dt>
      <dd><code><?= myronEscape((string) ($_GET['resource'] ?? '')) ?></code></dd>
      <dt>Scopes</dt>
      <dd><?= myronEscape(implode(', ', $scopes)) ?></dd>
    </dl>
    <form method="post" class="sg-card__actions">
      <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
      <?php foreach (['response_type', 'client_id', 'redirect_uri', 'resource', 'scope', 'state', 'code_challenge', 'code_challenge_method'] as $field): ?>
        <input type="hidden" name="<?= myronEscape($field) ?>" value="<?= myronEscape((string) ($_GET[$field] ?? '')) ?>">
      <?php endforeach; ?>
      <button class="sg-button sg-button--primary" type="submit" name="decision" value="approve">Authorize Connector</button>
      <button class="sg-button sg-button--secondary" type="submit" name="decision" value="deny">Deny</button>
    </form>
  </section>
</div>
<?php
myronRenderAdminShellEnd();
