All files / web/src/app/api/admin/songs route.ts

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

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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * Admin Songs API
 *
 * GET  /api/admin/songs — List all session songs with player/plan context
 * POST /api/admin/songs — Retry/regenerate songs or flag content issues
 */

import { desc, eq, inArray } from 'drizzle-orm'
import { stat } from 'fs/promises'
import { NextResponse } from 'next/server'
import path from 'path'
import { db, schema } from '@/db'
import { withAuth } from '@/lib/auth/withAuth'
import {
  getAdminSongPlanSummary,
  getSongPlanValidationSummary,
} from '@/lib/session-song/admin-validation-summary'
import { parseSongPlan } from '@/lib/song-share/songPlan'
import {
  retrySessionSongGeneration,
  type SessionSongRegenerationMode,
} from '@/lib/tasks/session-song'

export const GET = withAuth(
  async (request) => {
    try {
      const url = new URL(request.url)
      const limit = Math.min(parseInt(url.searchParams.get('limit') ?? '50', 10), 200)
      const statusFilter = url.searchParams.get('status')

      const allSongs = await db
        .select({
          id: schema.sessionSongs.id,
          sessionPlanId: schema.sessionSongs.sessionPlanId,
          playerId: schema.sessionSongs.playerId,
          status: schema.sessionSongs.status,
          promptInput: schema.sessionSongs.promptInput,
          llmOutput: schema.sessionSongs.llmOutput,
          localFilePath: schema.sessionSongs.localFilePath,
          durationSeconds: schema.sessionSongs.durationSeconds,
          errorMessage: schema.sessionSongs.errorMessage,
          failureKind: schema.sessionSongs.failureKind,
          backgroundTaskId: schema.sessionSongs.backgroundTaskId,
          triggerSource: schema.sessionSongs.triggerSource,
          contentReviewStatus: schema.sessionSongs.contentReviewStatus,
          contentReviewNote: schema.sessionSongs.contentReviewNote,
          contentReviewedAt: schema.sessionSongs.contentReviewedAt,
          contentReviewedBy: schema.sessionSongs.contentReviewedBy,
          regenerationCount: schema.sessionSongs.regenerationCount,
          lastRegenerationReason: schema.sessionSongs.lastRegenerationReason,
          lastRegenerationAt: schema.sessionSongs.lastRegenerationAt,
          createdAt: schema.sessionSongs.createdAt,
          completedAt: schema.sessionSongs.completedAt,
        })
        .from(schema.sessionSongs)
        .orderBy(desc(schema.sessionSongs.createdAt))
        .limit(limit)

      // Filter in JS (simpler than building dynamic SQL for optional filter)
      const filtered = statusFilter ? allSongs.filter((s) => s.status === statusFilter) : allSongs

      // Fetch player names for all songs
      const playerIds = [...new Set(filtered.map((s) => s.playerId))]
      const allPlayers =
        playerIds.length > 0
          ? await db
              .select({
                id: schema.players.id,
                name: schema.players.name,
                emoji: schema.players.emoji,
              })
              .from(schema.players)
              .where(
                playerIds.length === 1
                  ? eq(schema.players.id, playerIds[0])
                  : inArray(schema.players.id, playerIds)
              )
          : []

      const playerMap = new Map(allPlayers.map((p) => [p.id, p]))

      // Alignment sidecar lives next to the MP3 as `<songId>.json` — same dir
      // the public alignment route reads from.
      const songsDir = path.join(process.cwd(), 'data', 'audio', 'songs')

      // Check file existence for completed songs
      const songs = await Promise.all(
        filtered.map(async (song) => {
          let fileExists = false
          let fileSizeBytes: number | null = null

          if (song.localFilePath) {
            try {
              const stats = await stat(song.localFilePath)
              fileExists = true
              fileSizeBytes = stats.size
            } catch {
              fileExists = false
            }
          }

          let alignmentExists = false
          if (song.status === 'completed') {
            try {
              await stat(path.join(songsDir, `${song.id}.json`))
              alignmentExists = true
            } catch {
              alignmentExists = false
            }
          }

          const player = playerMap.get(song.playerId)
          const planSummary = getAdminSongPlanSummary(song.llmOutput)
          const validationSummary = getSongPlanValidationSummary(song.llmOutput)
          const parsedPlan = parseSongPlan(song.llmOutput)
          // Shape down to what SyncedLyricsPlayer accepts.
          const lyrics =
            song.status === 'completed'
              ? parsedPlan.sections.map((s) => ({
                  name: s.name,
                  lines: s.lines,
                  durationMs: s.durationMs,
                }))
              : []

          return {
            id: song.id,
            sessionPlanId: song.sessionPlanId,
            playerId: song.playerId,
            playerName: player?.name ?? 'Unknown',
            playerEmoji: player?.emoji ?? '',
            status: song.status,
            title: planSummary.title,
            triggerSource: song.triggerSource,
            errorMessage: song.errorMessage,
            failureKind: song.failureKind,
            backgroundTaskId: song.backgroundTaskId,
            contentReviewStatus: song.contentReviewStatus,
            contentReviewNote: song.contentReviewNote,
            contentReviewedAt: song.contentReviewedAt,
            contentReviewedBy: song.contentReviewedBy,
            regenerationCount: song.regenerationCount,
            lastRegenerationReason: song.lastRegenerationReason,
            lastRegenerationAt: song.lastRegenerationAt,
            fileExists,
            fileSizeBytes,
            alignmentExists,
            lyrics,
            durationSeconds: song.durationSeconds,
            createdAt: song.createdAt,
            completedAt: song.completedAt,
            // Composition plan observability
            styles: planSummary.styles,
            totalDurationMs: planSummary.totalDurationMs,
            sectionSummary: planSummary.sectionSummary,
            ...validationSummary,
            // Full data for detail view
            promptInput: song.promptInput,
            llmOutput: song.llmOutput,
          }
        })
      )

      // Aggregate stats
      const stats = {
        total: allSongs.length,
        completed: allSongs.filter((s) => s.status === 'completed').length,
        failed: allSongs.filter((s) => s.status === 'failed').length,
        flagged: allSongs.filter((s) => s.contentReviewStatus === 'flagged').length,
        generating: allSongs.filter(
          (s) =>
            s.status === 'pending' || s.status === 'prompt_generating' || s.status === 'generating'
        ).length,
        validationFlagged: songs.filter((s) => s.validationIssueCount > 0).length,
        validationRepaired: songs.filter((s) => s.validationOutcome === 'repaired').length,
        validationFallback: songs.filter((s) => s.validationOutcome === 'fallback').length,
        validationBlocked: songs.filter((s) => s.validationOutcome === 'blocked').length,
      }

      return NextResponse.json({ songs, stats })
    } catch (error) {
      console.error('[admin/songs] Failed to fetch songs:', error)
      return NextResponse.json({ error: 'Failed to fetch songs' }, { status: 500 })
    }
  },
  { role: 'admin' }
)

export const POST = withAuth(
  async (request, { userId }) => {
    const body = await request.json()
    const { songId, action } = body as {
      songId: string
      action: string
      mode?: SessionSongRegenerationMode
      reason?: string
    }

    if (!songId) {
      return NextResponse.json({ error: 'Song ID is required' }, { status: 400 })
    }

    if (!['retry', 'regenerate', 'flag_content', 'clear_content_flag'].includes(action)) {
      return NextResponse.json({ error: 'Unknown action' }, { status: 400 })
    }

    // Look up the song
    const [song] = await db
      .select()
      .from(schema.sessionSongs)
      .where(eq(schema.sessionSongs.id, songId))
      .limit(1)

    if (!song) {
      return NextResponse.json({ error: 'Song not found' }, { status: 404 })
    }

    if (action === 'flag_content') {
      const reason = typeof body.reason === 'string' ? body.reason.trim() : ''
      if (!reason) {
        return NextResponse.json({ error: 'Flag reason is required' }, { status: 400 })
      }

      await db
        .update(schema.sessionSongs)
        .set({
          contentReviewStatus: 'flagged',
          contentReviewNote: reason,
          contentReviewedAt: new Date(),
          contentReviewedBy: userId,
        })
        .where(eq(schema.sessionSongs.id, songId))

      return NextResponse.json({ ok: true })
    }

    if (action === 'clear_content_flag') {
      await db
        .update(schema.sessionSongs)
        .set({
          contentReviewStatus: 'none',
          contentReviewNote: null,
          contentReviewedAt: new Date(),
          contentReviewedBy: userId,
        })
        .where(eq(schema.sessionSongs.id, songId))

      return NextResponse.json({ ok: true })
    }

    const requestedMode = body.mode ?? (action === 'regenerate' ? 'regenerate_prompt' : 'auto')
    if (!['auto', 'reuse_prompt', 'regenerate_prompt'].includes(requestedMode)) {
      return NextResponse.json({ error: 'Invalid regeneration mode' }, { status: 400 })
    }

    const result = await retrySessionSongGeneration(songId, {
      mode: requestedMode,
      reason: typeof body.reason === 'string' ? body.reason : undefined,
      userId,
    })

    return NextResponse.json({
      ok: true,
      songId: result.songId,
      taskId: result.taskId,
      mode: result.mode,
    })
  },
  { role: 'admin' }
)