// apps/web/src/server/db/pii-write.ts
import type { SQL } from 'drizzle-orm';
import { blindIndex, encrypt } from '@/server/db/crypto.js';

export interface PhonePatch {
  phone: SQL | string | null;
  phoneIndex: string | null;
  phoneHint: string | null;
}
export interface EmailPatch {
  email: SQL | string | null;
  emailIndex: string | null;
}

/**
 * Assemble the coupled phone columns. `value` MUST be the canonical E.164 form
 * with leading '+' (e.g. '+972501234567') — same string Firebase issues and the
 * admin search hashes via toE164IL(). null clears all three columns (never '' / '555').
 */
export async function setUserPhone(value: string | null, piiKey: string): Promise<PhonePatch> {
  if (!value) return { phone: null, phoneIndex: null, phoneHint: null };
  return {
    phone: encrypt(value, piiKey),
    phoneIndex: await blindIndex(value, piiKey),
    phoneHint: value.slice(-3),
  };
}

/**
 * Assemble the coupled email columns. Lowercases before hashing (mirror register.ts).
 * null clears both columns. Does NOT touch email_canonical_index (separate concern).
 */
export async function setUserEmail(value: string | null, piiKey: string): Promise<EmailPatch> {
  if (!value) return { email: null, emailIndex: null };
  const normalized = value.toLowerCase();
  return { email: encrypt(normalized, piiKey), emailIndex: await blindIndex(normalized, piiKey) };
}
