import { db } from '../db/db_index'
import { orders, orderItems, orderStatus, payments, refunds, couponUsage, complaints } from '../db/schema'
import { inArray } from 'drizzle-orm'

/**
 * Delete orders and all their related records
 * @param orderIds Array of order IDs to delete
 * @returns Promise<void>
 * @throws Error if deletion fails
 */
export async function deleteOrdersWithRelations(orderIds: number[]): Promise<void> {
  if (orderIds.length === 0) {
    return
  }

  // Delete child records first (in correct order to avoid FK constraint errors)

  // 1. Delete coupon usage records
  await db.delete(couponUsage).where(inArray(couponUsage.orderId, orderIds))

  // 2. Delete complaints related to these orders
  await db.delete(complaints).where(inArray(complaints.orderId, orderIds))

  // 3. Delete refunds
  await db.delete(refunds).where(inArray(refunds.orderId, orderIds))

  // 4. Delete payments
  await db.delete(payments).where(inArray(payments.orderId, orderIds))

  // 5. Delete order status records
  await db.delete(orderStatus).where(inArray(orderStatus.orderId, orderIds))

  // 6. Delete order items
  await db.delete(orderItems).where(inArray(orderItems.orderId, orderIds))

  // 7. Finally delete the orders themselves
  await db.delete(orders).where(inArray(orders.id, orderIds))
}
