All files / web/src/app/api/worksheets/skills/custom route.ts

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

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                                                                                                                                                                                                     
import { eq, and } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { db } from '@/db'
import { customSkills } from '@/db/schema'
import { getUserId } from '@/lib/viewer'
import { nanoid } from 'nanoid'
import { withAuth } from '@/lib/auth/withAuth'

/**
 * GET /api/worksheets/skills/custom
 *
 * Get all custom skills for the current user
 */
export const GET = withAuth(async (request) => {
  try {
    const userId = await getUserId()
    const { searchParams } = new URL(request.url)
    const operator = searchParams.get('operator') as 'addition' | 'subtraction' | null

    const query = operator
      ? and(eq(customSkills.userId, userId), eq(customSkills.operator, operator))
      : eq(customSkills.userId, userId)

    const skills = await db.query.customSkills.findMany({
      where: query,
      orderBy: (customSkills, { asc }) => [asc(customSkills.createdAt)],
    })

    // Parse JSON fields
    const parsed = skills.map((skill) => ({
      ...skill,
      digitRange: JSON.parse(skill.digitRange),
      regroupingConfig: JSON.parse(skill.regroupingConfig),
      displayRules: JSON.parse(skill.displayRules),
    }))

    return NextResponse.json({ skills: parsed })
  } catch (error) {
    console.error('Failed to fetch custom skills:', error)
    return NextResponse.json({ error: 'Failed to fetch custom skills' }, { status: 500 })
  }
})

/**
 * POST /api/worksheets/skills/custom
 *
 * Create a new custom skill
 */
export const POST = withAuth(async (request) => {
  try {
    const userId = await getUserId()
    const body = await request.json()

    const { name, description, operator, digitRange, regroupingConfig, displayRules } = body

    // Validate required fields
    if (!name || !operator || !digitRange || !regroupingConfig || !displayRules) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 })
    }

    // Validate operator
    if (operator !== 'addition' && operator !== 'subtraction') {
      return NextResponse.json({ error: 'Invalid operator' }, { status: 400 })
    }

    // Generate ID with custom prefix
    const id = `custom-${nanoid(10)}`
    const now = new Date().toISOString()

    const newSkill = {
      id,
      userId: userId,
      operator,
      name,
      description: description || null,
      digitRange: JSON.stringify(digitRange),
      regroupingConfig: JSON.stringify(regroupingConfig),
      displayRules: JSON.stringify(displayRules),
      createdAt: now,
      updatedAt: now,
    }

    await db.insert(customSkills).values(newSkill)

    // Return parsed skill
    return NextResponse.json({
      skill: {
        ...newSkill,
        digitRange,
        regroupingConfig,
        displayRules,
      },
    })
  } catch (error) {
    console.error('Failed to create custom skill:', error)
    return NextResponse.json({ error: 'Failed to create custom skill' }, { status: 500 })
  }
})