← back to Norma

app/api/gmail/messages/[id]/assign/route.ts

66 lines

// POST /api/gmail/messages/[id]/assign — admin assigns a message to a staff/intern.
// Body: { userId: string | null }  (null = unassign)

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

export const runtime = 'nodejs';

export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const auth = requireRole(request, 'admin');
  if (auth instanceof NextResponse) return auth;

  const { id } = await params;
  if (!id) return NextResponse.json({ error: 'missing id' }, { status: 400 });

  let body: { userId?: string | null };
  try { body = await request.json(); } catch { body = {}; }
  const userId = body.userId ?? null;

  // Look up the assigning admin's id from username
  const adminRow = await query<{ id: string }>(
    `SELECT id FROM tier_credentials WHERE username = $1 LIMIT 1`,
    [auth.username],
  );
  const assignedBy = adminRow.rows[0]?.id || null;

  // If assigning (not null), validate the target user exists + is active staff/intern
  if (userId !== null) {
    const userRow = await query<{ id: string; role: string }>(
      `SELECT id, role FROM tier_credentials
        WHERE id = $1 AND role IN ('admin','staff','intern')
        LIMIT 1`,
      [userId],
    );
    if (userRow.rows.length === 0) {
      return NextResponse.json({ error: 'user not found or not assignable' }, { status: 404 });
    }
  }

  const updateRes = await query<{
    id: string;
    assigned_user_id: string | null;
    assigned_at: string | null;
  }>(
    `UPDATE gmail_messages
        SET assigned_user_id = $1,
            assigned_at      = CASE WHEN $1 IS NULL THEN NULL ELSE NOW() END,
            assigned_by      = $2
      WHERE id = $3
      RETURNING id, assigned_user_id, assigned_at`,
    [userId, assignedBy, id],
  );

  if (updateRes.rows.length === 0) {
    return NextResponse.json({ error: 'message not found' }, { status: 404 });
  }

  return NextResponse.json({
    ok: true,
    message_id: id,
    assigned_user_id: updateRes.rows[0].assigned_user_id,
    assigned_at: updateRes.rows[0].assigned_at,
  });
}