import { NextResponse } from 'next/server'
import { createClient as createSupabaseClient } from '@/lib/auth/server'
import { createClient as createDeepgramClient } from '@deepgram/sdk'

const TOKEN_TTL_SECONDS = 600               // Token geldig voor 10 min (korter = veiliger)

export async function POST() {
  console.log('[API /deepgram/token] POST request received')
  try {
    const skipAuthCheck = process.env.SKIP_AUTH_CHECK === 'true'

    // Auth check (skip in development/demo mode)
    if (!skipAuthCheck) {
      console.log('[API /deepgram/token] Checking auth...')
      const supabase = await createSupabaseClient()
      const { data: authData, error: authError } = await supabase.auth.getUser()

      if (authError) {
        console.error('[API /deepgram/token] Auth error:', authError)
        return NextResponse.json(
          { error: 'Kon sessie niet ophalen' },
          { status: 500 }
        )
      }

      if (!authData?.user) {
        console.log('[API /deepgram/token] No user found - returning 401')
        return NextResponse.json({ error: 'Niet geautoriseerd' }, { status: 401 })
      }

      console.log('[API /deepgram/token] Auth OK')
    } else {
      console.log('[API /deepgram/token] Auth check skipped (SKIP_AUTH_CHECK=true)')
    }

    // Prefer admin key (can generate tokens), fallback to regular key
    const apiKey = process.env.DEEPGRAM_ADMIN_API_KEY || process.env.DEEPGRAM_API_KEY
    const keyType = process.env.DEEPGRAM_ADMIN_API_KEY ? 'ADMIN' : 'REGULAR'
    console.log('[API /deepgram/token] Using', keyType, 'API key, present:', !!apiKey)

    if (!apiKey) {
      console.error('[API /deepgram/token] No Deepgram API key configured!')
      return NextResponse.json(
        { error: 'Deepgram API key ontbreekt in server configuratie' },
        { status: 500 }
      )
    }

    // Check if we should use direct API key (for development when grantToken doesn't work)
    const useDirectKey = process.env.DEEPGRAM_USE_DIRECT_KEY === 'true'

    if (useDirectKey) {
      console.log('[API /deepgram/token] Using direct API key (DEEPGRAM_USE_DIRECT_KEY=true)')
      return NextResponse.json(
        {
          token: apiKey,
          expiresIn: TOKEN_TTL_SECONDS,
          authMode: 'apiKey',
        },
        { status: 200 }
      )
    }

    console.log('[API /deepgram/token] Requesting token from Deepgram...')
    console.log('[API /deepgram/token] API key length:', apiKey.length, 'starts with:', apiKey.slice(0, 8))
    const deepgram = createDeepgramClient(apiKey)

    let tokenResponse
    try {
      tokenResponse = await deepgram.auth.grantToken({
        ttl_seconds: TOKEN_TTL_SECONDS,
      })
      console.log('[API /deepgram/token] Deepgram response:', JSON.stringify(tokenResponse, null, 2))
    } catch (deepgramError) {
      console.error('[API /deepgram/token] Deepgram SDK threw error:', deepgramError)
      return NextResponse.json(
        { error: 'Deepgram SDK error: ' + (deepgramError instanceof Error ? deepgramError.message : String(deepgramError)) },
        { status: 502 }
      )
    }

    if (!tokenResponse.result) {
      console.error('[API /deepgram/token] Deepgram API error - no result. Full response:', tokenResponse)
      console.log('[API /deepgram/token] TIP: Set DEEPGRAM_USE_DIRECT_KEY=true in .env.local to use API key directly')
      return NextResponse.json(
        { error: 'Genereren van tijdelijk token mislukt', details: tokenResponse.error },
        { status: 502 }
      )
    }

    console.log('[API /deepgram/token] Token generated successfully, expiresIn:', tokenResponse.result.expires_in)
    return NextResponse.json(
      {
        token: tokenResponse.result.access_token,
        expiresIn: tokenResponse.result.expires_in,
        authMode: 'accessToken',
      },
      { status: 200 }
    )
  } catch (error) {
    console.error('[API /deepgram/token] Unexpected error:', error)
    return NextResponse.json(
      { error: 'Onverwachte fout bij genereren token' },
      { status: 500 }
    )
  }
}
