All files / web/src/app/api/flowchart-workshop/sessions route.ts

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

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

/**
 * GET /api/flowchart-workshop/sessions
 * List current user's active workshop sessions
 *
 * Returns: { sessions: WorkshopSession[] }
 */
export const GET = withAuth(async () => {
  try {
    const userId = await getUserId()
    const now = new Date()

    // Get non-expired sessions
    const sessions = await db.query.workshopSessions.findMany({
      where: and(
        eq(schema.workshopSessions.userId, userId),
        gt(schema.workshopSessions.expiresAt, now)
      ),
      orderBy: [desc(schema.workshopSessions.updatedAt)],
      columns: {
        id: true,
        state: true,
        topicDescription: true,
        flowchartId: true,
        remixFromId: true,
        draftTitle: true,
        draftDescription: true,
        draftEmoji: true,
        draftDifficulty: true,
        draftDefinitionJson: true,
        draftMermaidContent: true,
        createdAt: true,
        updatedAt: true,
        expiresAt: true,
      },
    })

    return NextResponse.json({ sessions })
  } catch (error) {
    console.error('Failed to list workshop sessions:', error)
    return NextResponse.json({ error: 'Failed to list sessions' }, { status: 500 })
  }
})

/**
 * POST /api/flowchart-workshop/sessions
 * Create a new workshop session
 *
 * Body: {
 *   topicDescription?: string - Initial topic description
 *   remixFromId?: string - ID of flowchart to remix from (hardcoded or database)
 *   flowchartId?: string - ID of existing teacher flowchart to edit (creates new on publish)
 *   editPublishedId?: string - ID of own published flowchart to edit (updates on publish)
 * }
 *
 * Returns: { session: WorkshopSession }
 */
export const POST = withAuth(async (request) => {
  try {
    const userId = await getUserId()
    const body = await request.json()

    const now = new Date()
    const expiresAt = new Date()
    expiresAt.setDate(expiresAt.getDate() + 7) // 7-day expiry

    // Determine initial state
    let initialState: 'initial' | 'refining' = 'initial'
    let draftDefinitionJson: string | null = null
    let draftMermaidContent: string | null = null
    let draftTitle: string | null = null
    let draftDescription: string | null = null
    let draftEmoji: string | null = null
    let draftDifficulty: 'Beginner' | 'Intermediate' | 'Advanced' | null = null
    let linkedPublishedId: string | null = null
    let topicDescription: string | null = body.topicDescription || null

    // If editing a published flowchart (edit-in-place workflow)
    if (body.editPublishedId) {
      const existing = await db.query.teacherFlowcharts.findFirst({
        where: and(
          eq(schema.teacherFlowcharts.id, body.editPublishedId),
          eq(schema.teacherFlowcharts.userId, userId),
          eq(schema.teacherFlowcharts.status, 'published')
        ),
      })

      if (!existing) {
        return NextResponse.json(
          { error: 'Flowchart not found or not owned by you' },
          { status: 404 }
        )
      }

      initialState = 'refining'
      draftDefinitionJson = existing.definitionJson
      draftMermaidContent = existing.mermaidContent
      draftTitle = existing.title // Keep same title (no "(Copy)")
      draftDescription = existing.description
      draftEmoji = existing.emoji
      draftDifficulty = existing.difficulty as typeof draftDifficulty
      linkedPublishedId = existing.id // This tells publish to UPDATE instead of INSERT
    }

    // If editing an existing flowchart (legacy path), load its data as the draft
    if (body.flowchartId && !linkedPublishedId) {
      const existing = await db.query.teacherFlowcharts.findFirst({
        where: and(
          eq(schema.teacherFlowcharts.id, body.flowchartId),
          eq(schema.teacherFlowcharts.userId, userId)
        ),
      })

      if (existing) {
        initialState = 'refining'
        draftDefinitionJson = existing.definitionJson
        draftMermaidContent = existing.mermaidContent
        draftTitle = existing.title
        draftDescription = existing.description
        draftEmoji = existing.emoji
        draftDifficulty = existing.difficulty as typeof draftDifficulty
      }
    }

    // If remixing from an existing flowchart, load it as the starting point
    // All flowcharts are now in the database (after seeding)
    if (body.remixFromId && !draftDefinitionJson) {
      const dbFlowchart = await db.query.teacherFlowcharts.findFirst({
        where: and(
          eq(schema.teacherFlowcharts.id, body.remixFromId),
          eq(schema.teacherFlowcharts.status, 'published')
        ),
      })

      if (dbFlowchart) {
        initialState = 'refining'
        draftDefinitionJson = dbFlowchart.definitionJson
        draftMermaidContent = dbFlowchart.mermaidContent
        draftTitle = `${dbFlowchart.title} (Copy)`
        draftDescription = dbFlowchart.description
        draftEmoji = dbFlowchart.emoji
        draftDifficulty = dbFlowchart.difficulty as typeof draftDifficulty
        topicDescription = dbFlowchart.description // Use description as topic for remixes
      }
    }

    const [session] = await db
      .insert(schema.workshopSessions)
      .values({
        userId,
        state: initialState,
        topicDescription,
        remixFromId: body.remixFromId || null,
        flowchartId: body.flowchartId || null,
        linkedPublishedId,
        draftDefinitionJson,
        draftMermaidContent,
        draftTitle,
        draftDescription,
        draftEmoji,
        draftDifficulty,
        refinementHistory: JSON.stringify([]),
        createdAt: now,
        updatedAt: now,
        expiresAt,
      })
      .returning()

    return NextResponse.json({ session }, { status: 201 })
  } catch (error) {
    console.error('Failed to create workshop session:', error)
    return NextResponse.json({ error: 'Failed to create session' }, { status: 500 })
  }
})