import { useDB, eq } from '../../utils/database'
import { customers } from '../schema'

export interface InsertCustomer {
  id: string
  userId: string
}

export interface Customer {
  id: string
  userId: string | null
  createdAt: Date | null
  updatedAt: Date | null
}

/**
 * Get customer by user ID (supports both org-enabled and org-disabled modes)
 * When organizations are disabled, userId represents the actual user
 * When organizations are enabled, userId should be the organization ID
 */
export const getCustomerByUserId = async (userId: string): Promise<Customer | undefined> => {
  try {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const db = useDB() as any
    const customer = await db.query.customers.findFirst({
      where: eq(customers.userId, userId)
    })
    return customer
  } catch (error) {
    console.error('[getCustomerByUserId]', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to find customer by user ID'
    })
  }
}

export const createCustomer = async (
  payload: InsertCustomer
): Promise<Customer> => {
  try {
    const db = useDB()
    const [customer] = await db
      .insert(customers)
      .values(payload)
      .returning()
    return customer as Customer
  } catch (error) {
    console.error('[createCustomer]', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to create customer'
    })
  }
}

export const getCustomerById = async (id: string): Promise<Customer | undefined> => {
  try {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const db = useDB() as any
    const customer = await db.query.customers.findFirst({
      where: eq(customers.id, id)
    })
    return customer
  } catch (error) {
    console.error('[getCustomerById]', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to find customer by ID'
    })
  }
}
