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

/**
 * 把 canonical patient row 的派生属性并入 patients.preferences(Json)——零 schema 迁移。
 *
 * 当前承载:
 *   - dedicatedCs 专属客服(current_task_director)：路由/指派属性,非画像特征。
 *     "当前"会换 → upsert 覆盖(存当前值)。用于详情页展示 + 推送人匹配。
 *   - contactPhone 默认联系号的关系语义(FRIDAY customer_contacts.relationship):
 *     { relationshipCode: host 原码, isSelf: 码=='1'(统计自证:成人 78.7%=本人) }。
 *     触达场景先能区分"本人号 vs 代接号"(儿童过半非本人号);完整关系标签待 host
 *     sys_dict 字典解码后由 assembler enum_mapping 补,此处零改动。
 *
 * 返回 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 };
  }

  const relCode = c.phoneRelationshipCode == null ? '' : String(c.phoneRelationshipCode).trim();
  if (relCode) {
    base.contactPhone = { relationshipCode: relCode, isSelf: relCode === '1' };
  }

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