import { describe, expect, it } from 'vitest'
import { deliveryAfterEmailChange, effectiveIdentity, emailTaken, tidyPhone } from '@/lib/domain/account'

/** Profile → Account (Nash, 2026-09-23): change my sign-in email (verified link) and my phone (no verification). */
describe('effectiveIdentity', () => {
  const env = { id: 'u1', email: 'nash@old.com', phone: '111', name: 'Nash' }
  it('the account row wins over AUTH_USERS, blanks fall through', () => {
    expect(effectiveIdentity(env, null)).toEqual(env)
    expect(effectiveIdentity(env, { email: 'Nash@New.com ' })).toMatchObject({ email: 'nash@new.com', phone: '111', name: 'Nash' })
    expect(effectiveIdentity(env, { phone: '' })).toMatchObject({ phone: null })
    expect(effectiveIdentity(env, { phone: null, email: '' })).toMatchObject({ phone: '111', email: 'nash@old.com' })
  })
})

describe('emailTaken', () => {
  const known = [{ email: 'A@x.com', userId: 'u1' }, { email: 'b@x.com', userId: 'u2' }]
  it('is case-insensitive and ignores the caller', () => {
    expect(emailTaken(known, 'a@X.com', 'u1')).toBe(false)
    expect(emailTaken(known, 'a@x.com', 'u9')).toBe(true)
    expect(emailTaken(known, 'c@x.com', 'u9')).toBe(false)
  })
})

describe('phone + delivery', () => {
  it('phone is kept as typed; digits for matching', () => {
    expect(tidyPhone('  (555) 555-0100 ')).toEqual({ phone: '(555) 555-0100', digits: '5555550100' })
    expect(tidyPhone('+1 555 555 0100')).toEqual({ phone: '+1 555 555 0100', digits: '5555550100' })
    expect(tidyPhone('')).toEqual({ phone: null, digits: null })
    expect(tidyPhone('ext 12')).toEqual({ phone: 'ext 12', digits: null })
  })
  it('a delivery address that mirrored the old sign-in email follows the change', () => {
    expect(deliveryAfterEmailChange(null, 'a@x.com')).toBeNull()
    expect(deliveryAfterEmailChange('A@x.com', 'a@x.com')).toBeNull()
    expect(deliveryAfterEmailChange('other@y.com', 'a@x.com')).toBe('other@y.com')
  })
})
