/**
 * CSRF Token Endpoint
 *
 * GET /api/csrf-token
 *
 * Liefert ein neues CSRF-Token für Browser-basierte API-Aufrufe.
 * Das Token wird sowohl im Cookie als auch im Response-Body zurückgegeben.
 */

import { NextRequest, NextResponse } from 'next/server'
import { generateCsrfToken, CSRF_COOKIE, CSRF_HEADER_NAME } from '@/lib/security/csrf'
import { publicApiLimiter, getClientIp, rateLimitHeaders } from '@/lib/security/rate-limiter'

export async function GET(req: NextRequest): Promise<NextResponse> {
  // Rate-Limiting
  const ip = getClientIp(req.headers)
  const rateLimit = await publicApiLimiter.check(ip)

  if (!rateLimit.allowed) {
    return NextResponse.json(
      { error: 'Too many requests' },
      {
        status: 429,
        headers: rateLimitHeaders(rateLimit, 60),
      },
    )
  }

  // Neues Token generieren
  const token = generateCsrfToken()

  // Response mit Token
  const response = NextResponse.json({
    success: true,
    token,
    header: CSRF_HEADER_NAME,
    cookie: CSRF_COOKIE,
    usage: 'Include the token in both the X-CSRF-Token header and csrf-token cookie for POST/PUT/DELETE requests',
  })

  // Cookie setzen
  const tokenExpiry = 60 * 60 // 1 Stunde in Sekunden
  response.cookies.set(CSRF_COOKIE, token, {
    httpOnly: false, // JavaScript muss lesen können
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict',
    path: '/',
    maxAge: tokenExpiry,
  })

  // Token auch im Header
  response.headers.set(CSRF_HEADER_NAME, token)

  // Rate-Limit Headers
  const rlHeaders = rateLimitHeaders(rateLimit, 60)
  for (const [key, value] of Object.entries(rlHeaders)) {
    response.headers.set(key, value as string)
  }

  return response
}
