import { randomBytes } from 'crypto';
import { NextResponse } from 'next/server';
import { buildAuthorizeUrl } from '@/lib/discord-oauth';
import { redis } from '@/lib/redis';

const OAUTH_STATE_TTL_SECONDS = 600;

function oauthStateKey(state: string): string {
  return `webui:oauth:state:${state}`;
}

export async function GET() {
  const state = randomBytes(24).toString('hex');
  await redis.set(oauthStateKey(state), '1', 'EX', OAUTH_STATE_TTL_SECONDS);
  return NextResponse.redirect(buildAuthorizeUrl(state));
}
