/**
 * Add product to cart for testing
 */
import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import * as schema from '../server/database/schema'
import { eq } from 'drizzle-orm'

const { products, carts, cartItems, users } = schema

const connectionString = process.env.DATABASE_URL || 'postgresql://dev:dev_password_change_me@localhost:5432/experimenta_dev'
const client = postgres(connectionString)
const db = drizzle(client, { schema })

async function addToCart() {
  console.log('🛒 Adding products to cart for test user...')

  // Get any user (the first one)
  const user = await db.query.users.findFirst()

  if (!user) {
    console.error('❌ No users found. Please login first.')
    await client.end()
    process.exit(1)
  }

  console.log(`  ✓ Found user: ${user.email} (ID: ${user.id})`)

  // Get or create cart
  let cart = await db.query.carts.findFirst({
    where: eq(carts.userId, user.id),
  })

  if (!cart) {
    const [newCart] = await db.insert(carts).values({ userId: user.id }).returning()
    cart = newCart
    console.log(`  ✓ Created cart: ${cart.id}`)
  } else {
    console.log(`  ✓ Found cart: ${cart.id}`)
  }

  // Get first product
  const product = await db.query.products.findFirst({
    where: eq(products.active, true),
  })

  if (!product) {
    console.error('❌ No active products found.')
    await client.end()
    process.exit(1)
  }

  console.log(`  ✓ Found product: ${product.name} (${product.price}€)`)

  // Check if item already exists
  const existingItem = await db.query.cartItems.findFirst({
    where: (item, { and, eq }) => and(eq(item.cartId, cart.id), eq(item.productId, product.id)),
  })

  if (existingItem) {
    console.log(`  ℹ Product already in cart, skipping...`)
    console.log(`✅ Cart ready for checkout!`)
    await client.end()
    return
  }

  // Add to cart
  const [cartItem] = await db
    .insert(cartItems)
    .values({
      cartId: cart.id,
      productId: product.id,
      quantity: 2,
    })
    .returning()

  console.log(`  ✓ Added ${cartItem.quantity}x "${product.name}" to cart`)
  console.log(`✅ Cart ready for checkout!`)

  await client.end()
}

addToCart().catch((error) => {
  console.error('❌ Error:', error)
  process.exit(1)
})
