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

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

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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197                                                                                                                                                                                                                                                                                                                                                                                                         
import { eq, and } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { db, schema } from '@/db'
import { getUserId } from '@/lib/viewer'
import {
  parseAdditionConfig,
  serializeAdditionConfig,
  defaultAdditionConfig,
  additionConfigSchema,
} from '@/app/create/worksheets/config-schemas'
import {
  WORKSHEET_LIMITS,
  validateWorksheetLimits,
} from '@/app/create/worksheets/constants/validation'
import { withAuth } from '@/lib/auth/withAuth'

/**
 * GET /api/worksheets/settings?type=addition
 * Load user's saved worksheet settings
 *
 * Query params:
 *   - type: 'addition' | 'subtraction' | etc.
 *
 * Returns:
 *   - config: Parsed and validated config (latest version)
 *   - exists: boolean (true if user has saved settings)
 */
export const GET = withAuth(async (request) => {
  try {
    const userId = await getUserId()
    const { searchParams } = new URL(request.url)
    const worksheetType = searchParams.get('type')

    if (!worksheetType) {
      return NextResponse.json({ error: 'Missing type parameter' }, { status: 400 })
    }

    // Only 'addition' is supported for now
    if (worksheetType !== 'addition') {
      return NextResponse.json(
        { error: `Unsupported worksheet type: ${worksheetType}` },
        { status: 400 }
      )
    }

    // Look up user's saved settings
    const [row] = await db
      .select()
      .from(schema.worksheetSettings)
      .where(
        and(
          eq(schema.worksheetSettings.userId, userId),
          eq(schema.worksheetSettings.worksheetType, worksheetType)
        )
      )
      .limit(1)

    if (!row) {
      // No saved settings, return defaults
      return NextResponse.json({
        config: defaultAdditionConfig,
        exists: false,
      })
    }

    // Parse and validate config (auto-migrates to latest version)
    const config = parseAdditionConfig(row.config)

    return NextResponse.json({
      config,
      exists: true,
    })
  } catch (error: any) {
    console.error('Failed to load worksheet settings:', error)
    return NextResponse.json({ error: 'Failed to load worksheet settings' }, { status: 500 })
  }
})

/**
 * POST /api/worksheets/settings
 * Save user's worksheet settings
 *
 * Body:
 *   - type: 'addition' | 'subtraction' | etc.
 *   - config: Config object (version will be added automatically)
 *
 * Returns:
 *   - success: boolean
 *   - id: string (worksheet_settings row id)
 */
export const POST = withAuth(async (request) => {
  try {
    const userId = await getUserId()
    const body = await request.json()

    const { type: worksheetType, config } = body

    if (!worksheetType) {
      return NextResponse.json({ error: 'Missing type field' }, { status: 400 })
    }

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

    // Only 'addition' is supported for now
    if (worksheetType !== 'addition') {
      return NextResponse.json(
        { error: `Unsupported worksheet type: ${worksheetType}` },
        { status: 400 }
      )
    }

    // Validate worksheet limits before saving
    const validation = validateWorksheetLimits(config.problemsPerPage, config.pages)
    if (!validation.valid) {
      return NextResponse.json(
        {
          success: false,
          error: validation.error,
        },
        { status: 400 }
      )
    }

    // Validate against schema (this will check all field types and ranges)
    const schemaValidation = additionConfigSchema.safeParse({
      ...config,
      version: 4,
    })
    if (!schemaValidation.success) {
      const errorMessages = schemaValidation.error.issues
        .map((err) => `${err.path.join('.')}: ${err.message}`)
        .join(', ')
      return NextResponse.json(
        {
          success: false,
          error: `Invalid configuration: ${errorMessages}`,
        },
        { status: 400 }
      )
    }

    // Serialize config (adds version automatically)
    const configJson = serializeAdditionConfig(config)

    // Check if user already has settings for this type
    const [existing] = await db
      .select()
      .from(schema.worksheetSettings)
      .where(
        and(
          eq(schema.worksheetSettings.userId, userId),
          eq(schema.worksheetSettings.worksheetType, worksheetType)
        )
      )
      .limit(1)

    const now = new Date()

    if (existing) {
      // Update existing row
      await db
        .update(schema.worksheetSettings)
        .set({
          config: configJson,
          updatedAt: now,
        })
        .where(eq(schema.worksheetSettings.id, existing.id))

      return NextResponse.json({
        success: true,
        id: existing.id,
      })
    } else {
      // Insert new row
      const id = crypto.randomUUID()
      await db.insert(schema.worksheetSettings).values({
        id,
        userId: userId,
        worksheetType,
        config: configJson,
        createdAt: now,
        updatedAt: now,
      })

      return NextResponse.json({
        success: true,
        id,
      })
    }
  } catch (error: any) {
    console.error('Failed to save worksheet settings:', error)
    return NextResponse.json({ error: 'Failed to save worksheet settings' }, { status: 500 })
  }
})