import { deleteOrdersWithRelations } from '@/src/dbService'

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

  try {
    await deleteOrdersWithRelations(orderIds);
    console.log(`Successfully deleted ${orderIds.length} orders and all related records`);
  } catch (error) {
    console.error(`Failed to delete orders ${orderIds.join(', ')}:`, error);
    throw error;
  }
};

/*
// Old implementation - direct DB queries:
import { db } from '@/src/db/db_index'
import { orders, orderItems, orderStatus, payments, refunds, couponUsage, complaints } from '@/src/db/schema'
import { eq, inArray } from 'drizzle-orm';

export const deleteOrders = async (orderIds: number[]): Promise<void> => {
  if (orderIds.length === 0) {
    return;
  }

  try {
    // 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));
    
    console.log(`Successfully deleted ${orderIds.length} orders and all related records`);
  } catch (error) {
    console.error(`Failed to delete orders ${orderIds.join(', ')}:`, error);
    throw error;
  }
};
*/
