← back to Norma

app/api/xsessions/posts/route.ts

37 lines

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

/**
 * PATCH /api/xsessions/posts
 * Mark a post as "used" or "unused".
 * Body: { id: string, is_used: boolean }
 */
export async function PATCH(request: NextRequest) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  try {
    const body = await request.json();
    const { id, is_used } = body;

    if (!id) {
      return NextResponse.json({ error: 'Post id is required' }, { status: 400 });
    }

    const result = await query(
      `UPDATE x_posts SET is_used = $1 WHERE id = $2 RETURNING *`,
      [is_used ?? true, id]
    );

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

    return NextResponse.json({ post: result.rows[0] });
  } catch (err) {
    console.error('[api/xsessions/posts] PATCH error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to update post' }, { status: 500 });
  }
}