import { updateMailConnectionTitle } from "../../db/mail";

/**
 * PATCH /api/mail-connections/:id
 *
 * Setzt den user-definierten Anzeige-Titel einer MailConnection.
 *
 * Body:
 *   title?: string | null   — max 60 chars; leerer String → NULL (reset); null → NULL
 *
 * Response:
 *   200: { id, email, title }
 *   400: { error: 'TITLE_TOO_LONG' }
 *   404: { error: 'CONNECTION_NOT_FOUND' }
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const connectionId = getRouterParam(event, "id");

  if (!connectionId) {
    throw createError({ statusCode: 400, data: { error: "MISSING_ID" } });
  }

  const body = await readBody(event).catch(() => null);
  if (!body || !("title" in body)) {
    throw createError({ statusCode: 400, data: { error: "INVALID_BODY" } });
  }

  // Normalize: leerer String oder Whitespace-only → null (reset)
  let title: string | null = null;
  if (typeof body.title === "string") {
    const trimmed = body.title.trim();
    title = trimmed.length > 0 ? trimmed : null;
  }

  if (title !== null && title.length > 60) {
    throw createError({ statusCode: 400, data: { error: "TITLE_TOO_LONG", max: 60 } });
  }

  const result = await updateMailConnectionTitle(user.id, connectionId, title);

  if (!result) {
    throw createError({ statusCode: 404, data: { error: "CONNECTION_NOT_FOUND" } });
  }

  return { success: true, data: result };
});
