import { NextRequest, NextResponse } from 'next/server';

const getUrl = (request: NextRequest) => {
  return process.env.NEXT_PUBLIC_APP_URL || request.nextUrl.origin;
};

export async function GET(request: NextRequest) {
  const url = getUrl(request);
  try {
    const { searchParams } = new URL(request.url);
    const code = searchParams.get('code');
    const error = searchParams.get('error');
    const state = searchParams.get('state');

    // 处理用户拒绝授权的情况
    if (error) {
      console.error('Discord OAuth error:', error);
      return NextResponse.redirect(new URL(`${url}/login?error=discord_denied`, request.url));
    }

    // 检查授权码
    if (!code) {
      console.error('No authorization code received from Discord');
      return NextResponse.redirect(new URL(`${url}/login?error=discord_no_code`, request.url));
    }

    // 将code作为URL参数传递给前端登录页面处理
    const loginUrl = new URL(`${url}/login`, request.url);
    loginUrl.searchParams.set('discord_code', code);
    if (state) {
      loginUrl.searchParams.set('discord_state', state);
    }

    console.log('Discord OAuth callback successful, redirecting to login page with code');
    return NextResponse.redirect(loginUrl);
  } catch (error) {
    console.error('Discord OAuth callback error:', error);
    return NextResponse.redirect(new URL(`${url}/login?error=discord_callback_error`, request.url));
  }
}
