All files / web/src/app/api/worksheets/preview route.ts

0% Statements 0/72
0% Branches 0/1
0% Functions 0/1
0% Lines 0/72

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                                                                                                                                                 
import { NextResponse } from 'next/server'
import { generateWorksheetPreview } from '@/app/create/worksheets/generatePreview'
import type { WorksheetFormState } from '@/app/create/worksheets/types'
import { withAuth } from '@/lib/auth/withAuth'

export const dynamic = 'force-dynamic'

/**
 * POST /api/worksheets/preview
 * Generate a preview of a worksheet configuration
 */
export const POST = withAuth(async (request) => {
  try {
    const body = await request.json()
    const { config } = body as { config: WorksheetFormState }

    if (!config) {
      return NextResponse.json({ success: false, error: 'Missing config' }, { status: 400 })
    }

    // Calculate derived state fields
    const problemsPerPage = config.problemsPerPage ?? 20
    const pages = config.pages ?? 1
    const cols = config.cols ?? 5
    const rows = Math.ceil((problemsPerPage * pages) / cols)
    const total = problemsPerPage * pages

    // Add date, seed, and derived fields if missing
    const fullConfig: WorksheetFormState = {
      ...config,
      date:
        config.date ||
        new Date().toLocaleDateString('en-US', {
          month: 'long',
          day: 'numeric',
          year: 'numeric',
        }),
      seed: config.seed || Date.now() % 2147483647,
      rows,
      total,
    }

    // Generate preview
    const result = await generateWorksheetPreview(fullConfig)

    if (!result.success) {
      return NextResponse.json(
        {
          success: false,
          error: result.error,
          details: result.details,
        },
        { status: 422 }
      )
    }

    return NextResponse.json({
      success: true,
      pages: result.pages,
    })
  } catch (error) {
    console.error('Preview generation error:', error)
    return NextResponse.json(
      {
        success: false,
        error: 'Internal server error',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    )
  }
})