← back to Norma

app/api/xsessions/[id]/route.ts

65 lines

import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { requireRole } from '@/lib/require-role';

type RouteContext = { params: Promise<{ id: string }> };

/**
 * GET /api/xsessions/[id]
 * Fetch a single X session with all its posts.
 */
export async function GET(request: NextRequest, context: RouteContext) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  const { id } = await context.params;

  try {
    const sessionResult = await query(
      `SELECT * FROM x_sessions WHERE id = $1`, [id]
    );

    if (sessionResult.rowCount === 0) {
      return NextResponse.json({ error: 'Session not found' }, { status: 404 });
    }

    const postsResult = await query(
      `SELECT * FROM x_posts WHERE x_session_id = $1 ORDER BY posted_at DESC`, [id]
    );

    return NextResponse.json({
      session: { ...sessionResult.rows[0], posts: postsResult.rows },
    });
  } catch (err) {
    console.error('[api/xsessions/[id]] GET error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to fetch session' }, { status: 500 });
  }
}

/**
 * DELETE /api/xsessions/[id]
 * Delete a session and cascade-delete its posts.
 */
export async function DELETE(request: NextRequest, context: RouteContext) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  const { id } = await context.params;

  try {
    const result = await query(
      `DELETE FROM x_sessions WHERE id = $1 RETURNING id, status, post_count`,
      [id]
    );

    if (result.rowCount === 0) {
      return NextResponse.json({ error: 'Session not found' }, { status: 404 });
    }

    return NextResponse.json({ success: true, deleted: result.rows[0] });
  } catch (err) {
    console.error('[api/xsessions/[id]] DELETE error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to delete session' }, { status: 500 });
  }
}