/**
 * YouTube Token Refresh API
 *
 * Erneuert den Access Token für einen Social Account.
 *
 * POST /api/youtube/refresh-token
 * Body: { socialAccountId: number }
 */

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

const logger = createSafeLogger('API:YouTubeRefreshToken')

interface SocialAccountCredentials {
  accessToken?: string
  refreshToken?: string
  tokenExpiresAt?: string
}

interface SocialAccount {
  id: number
  displayName?: string
  credentials?: SocialAccountCredentials
}

export async function POST(req: NextRequest) {
  try {
    // CSRF-Schutz
    const csrfResult = validateCsrf(req)
    if (!csrfResult.valid) {
      logger.warn('CSRF validation failed', { reason: csrfResult.reason })
      return NextResponse.json({ error: 'CSRF validation failed' }, { status: 403 })
    }

    const payload = await getPayload({ config })

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

    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const body = await req.json()
    const { socialAccountId } = body

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

    // Account laden
    const account = (await payload.findByID({
      collection: 'social-accounts',
      id: socialAccountId,
    })) as SocialAccount | null

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

    if (!account.credentials?.refreshToken) {
      return NextResponse.json(
        { error: 'No refresh token available. Re-authenticate with YouTube.' },
        { status: 400 }
      )
    }

    // Token erneuern
    const credentials = await refreshAccessToken(account.credentials.refreshToken)

    // Account aktualisieren
    await payload.update({
      collection: 'social-accounts',
      id: socialAccountId,
      data: {
        credentials: {
          accessToken: credentials.access_token || undefined,
          refreshToken: credentials.refresh_token || account.credentials.refreshToken,
          tokenExpiresAt: credentials.expiry_date
            ? new Date(credentials.expiry_date).toISOString()
            : undefined,
        },
      },
    })

    logger.info('Token refreshed', {
      socialAccountId,
      displayName: account.displayName,
    })

    return NextResponse.json({
      success: true,
      expiresAt: credentials.expiry_date
        ? new Date(credentials.expiry_date).toISOString()
        : null,
    })
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error'
    logger.error('Token refresh error:', { error: errorMessage })

    // Bei bestimmten Fehlern genauere Meldung
    if (errorMessage.includes('invalid_grant')) {
      return NextResponse.json(
        { error: 'Refresh token invalid or revoked. Re-authenticate with YouTube.' },
        { status: 400 }
      )
    }

    return NextResponse.json({ error: errorMessage }, { status: 500 })
  }
}
