import { getDb } from '../db/client.js'

const sql = getDb()

export const updateCustomerDisplayName = async (customerId, displayName) => {
  const [customer] = await sql`
    UPDATE customers SET display_name = ${displayName}
    WHERE id = ${customerId}
    RETURNING id, display_name, is_anonymous, phone, created_at
  `
  return customer
}

// --- Phase 3.4: Self-Managed Auth ---

const CUSTOMER_SELECT = sql`id, display_name, is_anonymous, phone, email, google_sub, apple_sub, created_at`

export const getCustomerById = async (id) => {
  const [row] = await sql`SELECT ${CUSTOMER_SELECT} FROM customers WHERE id = ${id}`
  return row
}

export const getCustomerByPhone = async (phone) => {
  const [row] = await sql`SELECT ${CUSTOMER_SELECT} FROM customers WHERE phone = ${phone}`
  return row
}

export const getCustomerByGoogleSub = async (googleSub) => {
  const [row] = await sql`SELECT ${CUSTOMER_SELECT} FROM customers WHERE google_sub = ${googleSub}`
  return row
}

export const getCustomerByAppleSub = async (appleSub) => {
  const [row] = await sql`SELECT ${CUSTOMER_SELECT} FROM customers WHERE apple_sub = ${appleSub}`
  return row
}

export const createAnonymousCustomerV2 = async ({ display_name }) => {
  const [row] = await sql`
    INSERT INTO customers (display_name, is_anonymous)
    VALUES (${display_name}, true)
    RETURNING ${CUSTOMER_SELECT}
  `
  return row
}

export const createCustomerWithIdentity = async ({
  display_name,
  phone = null,
  email = null,
  google_sub = null,
  apple_sub = null,
}) => {
  const [row] = await sql`
    INSERT INTO customers (display_name, is_anonymous, phone, email, google_sub, apple_sub)
    VALUES (${display_name}, false, ${phone}, ${email}, ${google_sub}, ${apple_sub})
    RETURNING ${CUSTOMER_SELECT}
  `
  return row
}

export const upgradeCustomerIdentity = async (customerId, {
  phone,
  email,
  google_sub,
  apple_sub,
  display_name,
}) => {
  const [row] = await sql`
    UPDATE customers SET
      is_anonymous = false,
      phone = COALESCE(${phone ?? null}, phone),
      email = COALESCE(${email ?? null}, email),
      google_sub = COALESCE(${google_sub ?? null}, google_sub),
      apple_sub = COALESCE(${apple_sub ?? null}, apple_sub),
      display_name = COALESCE(${display_name ?? null}, display_name)
    WHERE id = ${customerId}
    RETURNING ${CUSTOMER_SELECT}
  `
  return row
}
