import { NextResponse } from 'next/server'

export async function GET() {
  try {
    // Get Discord OAuth settings directly from environment (most reliable)
    const clientId = process.env.DISCORD_CLIENT_ID
    const redirectUri = process.env.DISCORD_REDIRECT_URI || `${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/api/auth/discord/callback`

    console.log('[Auth] Discord OAuth - Client ID:', clientId ? `${clientId.substring(0, 5)}...` : 'NOT SET')
    console.log('[Auth] Discord OAuth - Redirect URI:', redirectUri)

    if (!clientId) {
      console.error('[Auth] DISCORD_CLIENT_ID is not configured in environment variables')
      return NextResponse.redirect(new URL('/auth/login?error=discord_not_configured', process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'))
    }

    // Build Discord OAuth URL
    const params = new URLSearchParams({
      client_id: clientId,
      redirect_uri: redirectUri,
      response_type: 'code',
      scope: 'identify email',
    })

    const discordAuthUrl = `https://discord.com/api/oauth2/authorize?${params.toString()}`
    console.log('[Auth] Redirecting to Discord:', discordAuthUrl)

    return NextResponse.redirect(discordAuthUrl)
  } catch (error) {
    console.error('[Auth] Discord OAuth error:', error)
    return NextResponse.redirect(new URL('/auth/login?error=oauth_failed', process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'))
  }
}
