// src/app/(frontend)/api/posts/route.ts
// Posts listing with category and type filters

import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import { getPostsByCategory } from '@/lib/search'
import type { Category } from '@/payload-types'
import {
  searchLimiter,
  rateLimitHeaders,
  getClientIpFromRequest,
  isIpBlocked,
} from '@/lib/security'

// Validation constants
const MAX_LIMIT = 50
const DEFAULT_LIMIT = 10
const POSTS_RATE_LIMIT = 30

export async function GET(request: NextRequest) {
  try {
    // IP-Blocklist prüfen
    const ip = getClientIpFromRequest(request)
    if (isIpBlocked(ip)) {
      return NextResponse.json(
        { error: 'Access denied' },
        { status: 403 },
      )
    }

    // Rate limiting (zentral)
    const rateLimit = await searchLimiter.check(ip)

    if (!rateLimit.allowed) {
      return NextResponse.json(
        { error: 'Too many requests. Please try again later.' },
        {
          status: 429,
          headers: rateLimitHeaders(rateLimit, POSTS_RATE_LIMIT),
        },
      )
    }

    // Parse query parameters
    const { searchParams } = new URL(request.url)
    const category = searchParams.get('category')?.trim()
    const type = searchParams.get('type')?.trim() as 'blog' | 'news' | 'press' | 'announcement' | undefined
    const tenantParam = searchParams.get('tenant')
    const pageParam = searchParams.get('page')
    const limitParam = searchParams.get('limit')
    const localeParam = searchParams.get('locale')?.trim()

    // Validate locale
    const validLocales = ['de', 'en']
    const locale = localeParam && validLocales.includes(localeParam) ? localeParam : 'de'

    // Validate type
    const validTypes = ['blog', 'news', 'press', 'announcement']
    if (type && !validTypes.includes(type)) {
      return NextResponse.json(
        { error: `Invalid type. Must be one of: ${validTypes.join(', ')}` },
        { status: 400 }
      )
    }

    // Parse numeric parameters
    const page = Math.max(1, parseInt(pageParam || '1', 10) || 1)
    const limit = Math.min(
      Math.max(1, parseInt(limitParam || String(DEFAULT_LIMIT), 10) || DEFAULT_LIMIT),
      MAX_LIMIT
    )
    const tenantId = tenantParam ? parseInt(tenantParam, 10) : undefined

    // Validate tenant ID if provided
    if (tenantParam && (isNaN(tenantId!) || tenantId! < 1)) {
      return NextResponse.json(
        { error: 'Invalid tenant ID' },
        { status: 400 }
      )
    }

    // Get payload instance
    const payload = await getPayload({ config })

    // Get posts
    const result = await getPostsByCategory(payload, {
      tenantId,
      categorySlug: category,
      type,
      locale,
      page,
      limit,
    })

    // Transform response
    const response = {
      docs: result.docs.map((post) => ({
        id: post.id,
        title: post.title,
        slug: post.slug,
        excerpt: post.excerpt || null,
        publishedAt: post.publishedAt || null,
        type: (post as typeof post & { type?: string }).type || 'blog',
        featuredImage: post.featuredImage && typeof post.featuredImage === 'object'
          ? {
              url: post.featuredImage.url,
              alt: post.featuredImage.alt,
              width: post.featuredImage.width,
              height: post.featuredImage.height,
            }
          : null,
        category: Array.isArray(post.categories) && post.categories.length > 0
          ? (() => {
              const firstCat = post.categories.find(
                (cat): cat is Category => cat !== null && typeof cat === 'object' && 'name' in cat
              )
              return firstCat ? { name: firstCat.name, slug: firstCat.slug } : null
            })()
          : null,
        categories: Array.isArray(post.categories)
          ? post.categories
              .filter((cat): cat is Category => cat !== null && typeof cat === 'object' && 'name' in cat)
              .map((cat) => ({ name: cat.name, slug: cat.slug }))
          : [],
      })),
      pagination: {
        page: result.page,
        limit,
        totalPages: result.totalPages,
        totalDocs: result.totalDocs,
        hasNextPage: result.hasNextPage,
        hasPrevPage: result.hasPrevPage,
      },
      filters: {
        category,
        type,
        locale,
        tenant: tenantId,
      },
    }

    return NextResponse.json(response, {
      headers: {
        ...rateLimitHeaders(rateLimit, POSTS_RATE_LIMIT),
        'Cache-Control': 'public, max-age=60, s-maxage=60',
      },
    })
  } catch (error) {
    console.error('[Posts API] Error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}
