/**
 * Meta OAuth Auth Initiation
 *
 * Startet den OAuth Flow für Facebook/Instagram Integration.
 *
 * GET /api/auth/meta?socialAccountId=123&accountType=both
 *
 * Query Parameters:
 * - socialAccountId: ID des Social Accounts (erforderlich)
 * - accountType: 'facebook' | 'instagram' | 'both' (optional, default: 'both')
 */

import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import { getAuthUrl, encodeState } from '@/lib/integrations/meta/oauth'
import { createSafeLogger } from '@/lib/security'
import type { MetaOAuthState } from '@/types/meta'

const logger = createSafeLogger('API:MetaAuth')

export async function GET(req: NextRequest) {
  try {
    const searchParams = req.nextUrl.searchParams
    const socialAccountId = searchParams.get('socialAccountId')
    const accountType = (searchParams.get('accountType') as MetaOAuthState['accountType']) || 'both'

    const baseUrl = process.env.NEXT_PUBLIC_SERVER_URL || ''

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

    // Validiere accountType
    if (!['facebook', 'instagram', 'both'].includes(accountType)) {
      return NextResponse.json(
        { error: 'Invalid accountType. Must be facebook, instagram, or both' },
        { status: 400 }
      )
    }

    const payload = await getPayload({ config })

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

    if (!user) {
      return NextResponse.redirect(
        `${baseUrl}/admin/login?redirect=/api/auth/meta?socialAccountId=${socialAccountId}&accountType=${accountType}`
      )
    }

    // 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 })
    }

    // Prüfen ob die Plattform Facebook oder Instagram ist
    const platform =
      typeof account.platform === 'object' && account.platform
        ? account.platform.slug
        : undefined
    if (!platform || !['facebook', 'instagram'].includes(platform)) {
      return NextResponse.json(
        { error: 'This endpoint is only for Facebook and Instagram accounts' },
        { status: 400 }
      )
    }

    // Auth URL generieren
    const authUrl = getAuthUrl({
      returnUrl: `/admin/collections/social-accounts/${socialAccountId}`,
      accountType,
      userId: (user as { id: number }).id,
      socialAccountId: parseInt(socialAccountId, 10),
    })

    // State separat loggen (ohne den vollen Token)
    logger.info('Meta OAuth initiated', {
      socialAccountId,
      userId: (user as { id: number }).id,
      platform,
      accountType,
    })

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

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