// Server-only — bidirectional sync between consultants and user_profiles.
// Call syncConsultantWithProfile after editing a consultant record.
// Call syncProfileToConsultant after editing a user_profiles record in admin.

import { createAdminClient } from '@/lib/supabase/admin'

export interface ConsultantUpdate {
  first_name?: string
  last_name?: string
  display_name?: string
  email?: string | null
}

/** Consultant edited → push name changes to linked user_profiles row. */
export async function syncConsultantWithProfile(
  consultantId: string,
  updates: ConsultantUpdate,
): Promise<void> {
  const admin = createAdminClient()

  const { data: consultant } = await admin
    .from('consultants')
    .select('auth_user_id')
    .eq('id', consultantId)
    .single()

  if (!consultant?.auth_user_id) return

  const profileUpdates: Record<string, unknown> = {}
  if (updates.first_name   !== undefined) profileUpdates.first_name   = updates.first_name
  if (updates.last_name    !== undefined) profileUpdates.last_name    = updates.last_name
  if (updates.display_name !== undefined) profileUpdates.display_name = updates.display_name

  if (Object.keys(profileUpdates).length === 0) return

  await admin
    .from('user_profiles')
    .update(profileUpdates)
    .eq('auth_user_id', consultant.auth_user_id)
}

/** user_profiles edited in admin → push name changes to linked consultants row. */
export async function syncProfileToConsultant(
  authUserId: string,
  updates: Pick<ConsultantUpdate, 'first_name' | 'last_name' | 'display_name'>,
): Promise<void> {
  const admin = createAdminClient()

  const consultantUpdates: Record<string, unknown> = {}
  if (updates.first_name   !== undefined) consultantUpdates.first_name   = updates.first_name
  if (updates.last_name    !== undefined) consultantUpdates.last_name    = updates.last_name
  if (updates.display_name !== undefined) consultantUpdates.display_name = updates.display_name

  if (Object.keys(consultantUpdates).length === 0) return

  await admin
    .from('consultants')
    .update(consultantUpdates)
    .eq('auth_user_id', authUserId)
}
