import { useDB, eq, asc } from '../../utils/database'
import { products, prices } from '../schema'

export interface InsertProduct {
  id: string
  name: string
  description?: string | null
  active: boolean
  image?: string | null
  metadata?: Record<string, unknown> | null
  features?: Array<{ name: string }> | null
}

export interface InsertPrice {
  id: string
  description?: string | null
  currency: string
  unitAmount: number
  type: string
  interval: string
  intervalCount: number
  trialPeriodDays?: number | null
  active: boolean
  metadata?: Record<string, unknown> | null
  productId: string
}

export const clearStripeData = async () => {
  const db = useDB()
  await db.delete(prices)
  await db.delete(products)
}

export const createStripeProduct = async (payload: InsertProduct) => {
  const db = useDB()
  const [product] = await db
    .insert(products)
    .values(payload)
    .returning()
  return product
}

export const createStripePrice = async (payload: InsertPrice) => {
  const db = useDB()
  const [price] = await db
    .insert(prices)
    .values(payload)
    .returning()
  return price
}

// These functions are used by the webhook handler
export const createOrUpdateStripeProduct = async (payload: InsertProduct) => {
  if (!payload.id) {
    throw new Error('Product ID is required')
  }

  const db = useDB()

  // First delete the existing product and its prices
  await db
    .delete(prices)
    .where(eq(prices.productId, payload.id))

  await db
    .delete(products)
    .where(eq(products.id, payload.id))

  // Then create fresh
  return createStripeProduct(payload)
}

export const createOrUpdateStripePrice = async (payload: InsertPrice) => {
  if (!payload.id) {
    throw new Error('Price ID is required')
  }

  const db = useDB()

  // First delete the existing price
  await db
    .delete(prices)
    .where(eq(prices.id, payload.id))

  // Then create fresh
  return createStripePrice(payload)
}

export const getAllPlans = async () => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const db = useDB() as any
  const plans = await db.query.prices.findMany({
    with: {
      product: true
    },
    orderBy: asc(prices.unitAmount)
  })
  return plans
}

export const deleteStripeProduct = async (id: string) => {
  const db = useDB()
  await db.delete(products).where(eq(products.id, id))
}

export const deleteStripePrice = async (id: string) => {
  const db = useDB()
  await db.delete(prices).where(eq(prices.id, id))
}
