export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig();

  // Generate state for CSRF protection
  const state = Math.random().toString(36).substring(7);

  // Store state in session (you'll need to implement session storage)
  setCookie(event, "oauth_state", state, {
    httpOnly: true,
    secure: true,
    sameSite: "lax",
    maxAge: 60 * 10, // 10 minutes
  });

  // Build OAuth authorization URL
  const params = new URLSearchParams({
    client_id: String(config.ghostguildClientId || ""),
    redirect_uri: `${config.public.siteUrl}/api/auth/callback`,
    response_type: "code",
    scope: "read:user read:member",
    state: state,
  });

  const authUrl = `${config.ghostguildApiUrl}/oauth/authorize?${params}`;

  // Redirect to Ghost Guild OAuth
  return sendRedirect(event, authUrl);
});
