import type { Prisma } from '@prisma/client';

/**
 * 把 canonical patient row 的派生属性并入 patients.preferences(Json)——零 schema 迁移。
 *
 * 当前承载:
 *   - dedicatedCs 专属客服(current_task_director)：路由/指派属性,非画像特征。
 *     "当前"会换 → upsert 覆盖(存当前值)。用于详情页展示 + 推送人匹配。
 *
 * 返回 undefined 表示"无可写偏好"(让 prisma upsert 不动该列)。
 */
export function mergePatientPreferences(
  c: Record<string, unknown>,
): Prisma.InputJsonValue | undefined {
  const base =
    c.preferences && typeof c.preferences === 'object'
      ? ({ ...(c.preferences as Record<string, unknown>) } as Record<string, unknown>)
      : ({} as Record<string, unknown>);

  const csName = ((c.dedicatedCsName as string | undefined) ?? '').trim() || null;
  const rawId = c.dedicatedCsId == null ? '' : String(c.dedicatedCsId).trim();
  const csId = rawId && rawId !== '0' ? rawId : null;
  if (csName || csId) {
    base.dedicatedCs = { id: csId, name: csName };
  }

  return Object.keys(base).length ? (base as Prisma.InputJsonValue) : undefined;
}
