// ============================================================
// PATCH /api/v1/conversations/{id}/assign
// Assigns or unassigns a conversation to an account member.
// Body: { assigned_agent_id: string | null }
// ============================================================

import { NextResponse } from 'next/server';
import { requireApiKey } from '@/lib/auth/api-context';
import { ok, fail, toApiErrorResponse } from '@/lib/api/v1/respond';

export async function PATCH(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const ctx = await requireApiKey(request, 'conversations:write');
    const { id } = await params;

    const body = (await request.json().catch(() => null)) as Record<
      string,
      unknown
    > | null;
    if (!body || typeof body !== 'object') {
      return fail('bad_request', 'Request body must be a JSON object', 400);
    }

    const assignedAgentId = body.assigned_agent_id ?? null;

    // Validate that the target user is a member of the account (if not null).
    if (assignedAgentId && typeof assignedAgentId === 'string') {
      const { data: memberRows, error: memberErr } = await ctx.supabase
        .from('profiles')
        .select('id')
        .eq('account_id', ctx.accountId)
        .eq('user_id', assignedAgentId)
        .limit(1);
      if (memberErr || !memberRows || memberRows.length === 0) {
        return fail(
          'bad_request',
          'assigned_agent_id is not a member of this account',
          400
        );
      }
    } else if (assignedAgentId !== null) {
      return fail(
        'bad_request',
        'assigned_agent_id must be a string or null',
        400
      );
    }

    const { data, error } = await ctx.supabase
      .from('conversations')
      .update({
        assigned_agent_id: assignedAgentId,
        updated_at: new Date().toISOString(),
      })
      .eq('id', id)
      .eq('account_id', ctx.accountId)
      .select('id, assigned_agent_id')
      .single();

    if (error) {
      console.error('[api/v1/conversations/assign] update error:', error);
      return fail('internal', 'Failed to assign conversation', 500);
    }
    if (!data) {
      return fail('not_found', 'Conversation not found', 404);
    }

    return ok({
      id: data.id,
      assigned_agent_id: data.assigned_agent_id,
    });
  } catch (err) {
    return toApiErrorResponse(err);
  }
}
