/**
 * YouTube OAuth Auth Initiation
 *
 * Startet den OAuth Flow für einen Social Account.
 *
 * GET /api/youtube/auth?socialAccountId=123
 */

import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import { getAuthUrl } from '@/lib/integrations/youtube/oauth'
import { createSafeLogger } from '@/lib/security'

const logger = createSafeLogger('API:YouTubeAuth')

export async function GET(req: NextRequest) {
  try {
    const searchParams = req.nextUrl.searchParams
    const socialAccountId = searchParams.get('socialAccountId')

    if (!socialAccountId) {
      return NextResponse.json(
        { error: 'socialAccountId query parameter required' },
        { status: 400 }
      )
    }

    const payload = await getPayload({ config })

    // Authentifizierung prüfen
    const { user } = await payload.auth({ headers: req.headers })

    if (!user) {
      return NextResponse.redirect(
        `${process.env.NEXT_PUBLIC_SERVER_URL}/admin/login?redirect=/api/youtube/auth?socialAccountId=${socialAccountId}`
      )
    }

    // Prüfen ob der Social Account existiert
    const account = await payload.findByID({
      collection: 'social-accounts',
      id: parseInt(socialAccountId, 10),
    })

    if (!account) {
      return NextResponse.json({ error: 'Social account not found' }, { status: 404 })
    }

    // State mit Account-ID erstellen (Base64 encoded)
    const state = Buffer.from(
      JSON.stringify({
        socialAccountId,
        userId: (user as { id: number }).id,
        timestamp: Date.now(),
      })
    ).toString('base64')

    const authUrl = getAuthUrl(state)

    logger.info('YouTube OAuth initiated', {
      socialAccountId,
      userId: (user as { id: number }).id,
    })

    return NextResponse.redirect(authUrl)
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error'
    logger.error('YouTube auth error:', { error: errorMessage })

    return NextResponse.redirect(
      `${process.env.NEXT_PUBLIC_SERVER_URL}/admin/collections/social-accounts?error=${encodeURIComponent(errorMessage)}`
    )
  }
}
