bookwiz.io / app / api / internal / process-word-count-queue / route.ts
route.ts
Raw
import { createServerSupabaseClient } from '@/lib/supabase'
import { NextResponse } from 'next/server'

// POST /api/internal/process-word-count-queue - Process queued word count recalculations
export async function POST(request: Request) {
  try {
    // Check for internal API key (optional security measure)
    const authHeader = request.headers.get('authorization')
    const expectedToken = process.env.INTERNAL_API_TOKEN
    
    if (expectedToken && authHeader !== `Bearer ${expectedToken}`) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      )
    }

    const supabase = createServerSupabaseClient()
    
    // Get batch size from query params or use default
    const url = new URL(request.url)
    const batchSize = parseInt(url.searchParams.get('batch_size') || '10')

    console.log(`Processing word count queue with batch size: ${batchSize}`)

    // Call the database function to process the queue
    const { data: results, error } = await supabase
      .rpc('process_word_count_queue', { batch_size: batchSize })

    if (error) {
      console.error('Error processing word count queue:', error)
      return NextResponse.json(
        { error: 'Failed to process word count queue' },
        { status: 500 }
      )
    }

    // Count successful and failed operations
    const successful = results?.filter((r: any) => r.success).length || 0
    const failed = results?.filter((r: any) => !r.success).length || 0

    console.log(`Word count queue processing complete: ${successful} successful, ${failed} failed`)

    // Log any failures
    if (failed > 0) {
      const failures = results?.filter((r: any) => !r.success) || []
      console.error('Word count processing failures:', failures)
    }

    return NextResponse.json({
      success: true,
      processed: results?.length || 0,
      successful,
      failed,
      results: results || []
    })

  } catch (error) {
    console.error('Error in process word count queue endpoint:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}

// GET /api/internal/process-word-count-queue - Get queue status
export async function GET(request: Request) {
  try {
    // Check for internal API key (optional security measure)
    const authHeader = request.headers.get('authorization')
    const expectedToken = process.env.INTERNAL_API_TOKEN
    
    if (expectedToken && authHeader !== `Bearer ${expectedToken}`) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      )
    }

    const supabase = createServerSupabaseClient()

    // Get queue statistics
    const { data: queueStats, error: statsError } = await supabase
      .from('book_word_count_queue')
      .select('*')

    if (statsError) {
      console.error('Error getting queue stats:', statsError)
      return NextResponse.json(
        { error: 'Failed to get queue statistics' },
        { status: 500 }
      )
    }

    const pending = queueStats?.filter(q => !q.processed_at).length || 0
    const processed = queueStats?.filter(q => q.processed_at).length || 0
    const failed = queueStats?.filter(q => q.attempts >= 3 && !q.processed_at).length || 0

    return NextResponse.json({
      success: true,
      queue_stats: {
        total: queueStats?.length || 0,
        pending,
        processed,
        failed
      },
      queue_items: queueStats || []
    })

  } catch (error) {
    console.error('Error in get queue status endpoint:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}