All files / web/src/app/api/flowcharts/seeds route.ts

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

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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import { NextResponse } from 'next/server'
import { eq, inArray } from 'drizzle-orm'
import { db, schema } from '@/db'
import { withAuth } from '@/lib/auth/withAuth'
import { FLOWCHART_SEEDS } from '@/lib/flowcharts/definitions'
import { getUserId } from '@/lib/viewer'

/**
 * Seed Status for a flowchart seed
 */
interface SeedStatus {
  id: string
  title: string
  emoji: string
  difficulty: string
  description: string
  /** Whether this seed exists in the database */
  isSeeded: boolean
  /** The database entry ID if seeded (may differ from seed ID) */
  databaseId?: string
  /** When the seed was added to the database */
  seededAt?: string
  /** Who seeded this flowchart */
  seededByUserId?: string
}

/**
 * GET /api/flowcharts/seeds
 *
 * List all available flowchart seeds and their database status.
 * Only available when visual debug is enabled.
 */
export const GET = withAuth(async () => {
  try {
    // Get seed IDs
    const seedIds = Object.keys(FLOWCHART_SEEDS)

    // Check which seeds are already in the database
    // Seeds are stored with their original ID as the primary key
    const existingSeeds = await db.query.teacherFlowcharts.findMany({
      where: inArray(schema.teacherFlowcharts.id, seedIds),
      columns: {
        id: true,
        userId: true,
        publishedAt: true,
      },
    })

    const seededMap = new Map(existingSeeds.map((s) => [s.id, s]))

    // Build status for each seed
    const seeds: SeedStatus[] = Object.entries(FLOWCHART_SEEDS).map(([id, seed]) => {
      const dbEntry = seededMap.get(id)
      return {
        id,
        title: seed.meta.title,
        emoji: seed.meta.emoji,
        difficulty: seed.meta.difficulty,
        description: seed.meta.description,
        isSeeded: !!dbEntry,
        databaseId: dbEntry?.id,
        seededAt: dbEntry?.publishedAt?.toISOString(),
        seededByUserId: dbEntry?.userId,
      }
    })

    return NextResponse.json({ seeds })
  } catch (error) {
    console.error('Failed to get seed status:', error)
    return NextResponse.json({ error: 'Failed to get seed status' }, { status: 500 })
  }
})

/**
 * POST /api/flowcharts/seeds
 *
 * Seed one or all flowcharts into the database.
 * The seeded flowcharts are owned by the current user.
 *
 * Body:
 * - action: 'seed' | 'seed-all' | 'reset'
 * - id?: string (required for 'seed' and 'reset')
 */
export const POST = withAuth(async (request) => {
  try {
    // Require authentication
    const userId = await getUserId()
    if (!userId) {
      return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
    }

    const body = await request.json()
    const { action, id } = body as { action: string; id?: string }

    if (action === 'seed') {
      if (!id) {
        return NextResponse.json({ error: 'Missing seed ID' }, { status: 400 })
      }

      const seed = FLOWCHART_SEEDS[id]
      if (!seed) {
        return NextResponse.json({ error: 'Unknown seed ID' }, { status: 404 })
      }

      // Check if already seeded
      const existing = await db.query.teacherFlowcharts.findFirst({
        where: eq(schema.teacherFlowcharts.id, id),
      })

      if (existing) {
        return NextResponse.json({ error: 'Seed already exists in database' }, { status: 409 })
      }

      // Insert the seed
      const now = new Date()
      await db.insert(schema.teacherFlowcharts).values({
        id, // Use the seed ID as the database ID
        userId,
        title: seed.meta.title,
        description: seed.meta.description,
        emoji: seed.meta.emoji,
        difficulty: seed.meta.difficulty,
        definitionJson: JSON.stringify(seed.definition),
        mermaidContent: seed.mermaid,
        status: 'published',
        publishedAt: now,
        searchKeywords: `${seed.meta.title} ${seed.meta.description}`.toLowerCase(),
        createdAt: now,
        updatedAt: now,
      })

      return NextResponse.json({ success: true, id })
    }

    if (action === 'seed-all') {
      const seedIds = Object.keys(FLOWCHART_SEEDS)

      // Check which seeds are already in the database
      const existingSeeds = await db.query.teacherFlowcharts.findMany({
        where: inArray(schema.teacherFlowcharts.id, seedIds),
        columns: { id: true },
      })
      const existingIds = new Set(existingSeeds.map((s) => s.id))

      // Filter to only unseeded
      const toSeed = seedIds.filter((seedId) => !existingIds.has(seedId))

      if (toSeed.length === 0) {
        return NextResponse.json({ success: true, seeded: [], message: 'All seeds already exist' })
      }

      // Insert all missing seeds
      const now = new Date()
      const values = toSeed.map((seedId) => {
        const seed = FLOWCHART_SEEDS[seedId]
        return {
          id: seedId,
          userId,
          title: seed.meta.title,
          description: seed.meta.description,
          emoji: seed.meta.emoji,
          difficulty: seed.meta.difficulty,
          definitionJson: JSON.stringify(seed.definition),
          mermaidContent: seed.mermaid,
          status: 'published' as const,
          publishedAt: now,
          searchKeywords: `${seed.meta.title} ${seed.meta.description}`.toLowerCase(),
          createdAt: now,
          updatedAt: now,
        }
      })

      await db.insert(schema.teacherFlowcharts).values(values)

      return NextResponse.json({ success: true, seeded: toSeed })
    }

    if (action === 'reset') {
      if (!id) {
        return NextResponse.json({ error: 'Missing seed ID' }, { status: 400 })
      }

      const seed = FLOWCHART_SEEDS[id]
      if (!seed) {
        return NextResponse.json({ error: 'Unknown seed ID' }, { status: 404 })
      }

      // Delete existing and re-insert
      await db.delete(schema.teacherFlowcharts).where(eq(schema.teacherFlowcharts.id, id))

      const now = new Date()
      await db.insert(schema.teacherFlowcharts).values({
        id,
        userId,
        title: seed.meta.title,
        description: seed.meta.description,
        emoji: seed.meta.emoji,
        difficulty: seed.meta.difficulty,
        definitionJson: JSON.stringify(seed.definition),
        mermaidContent: seed.mermaid,
        status: 'published',
        publishedAt: now,
        searchKeywords: `${seed.meta.title} ${seed.meta.description}`.toLowerCase(),
        createdAt: now,
        updatedAt: now,
      })

      return NextResponse.json({ success: true, id, action: 'reset' })
    }

    return NextResponse.json({ error: 'Unknown action' }, { status: 400 })
  } catch (error) {
    console.error('Failed to seed flowchart:', error)
    return NextResponse.json({ error: 'Failed to seed flowchart' }, { status: 500 })
  }
})