const { query } = require('../config/database')

async function getOrders(ctx) {
  const orders = await query('SELECT * FROM orders ORDER BY created_at DESC')
  
  ctx.body = {
    code: 200,
    data: orders
  }
}

async function getOrderById(ctx) {
  const orderId = ctx.params.id
  const orders = await query('SELECT * FROM orders WHERE id = ?', [orderId])
  
  if (orders.length > 0) {
    ctx.body = {
      code: 200,
      data: orders[0]
    }
  } else {
    ctx.body = {
      code: 404,
      message: '订单不存在'
    }
  }
}

async function createOrder(ctx) {
  const { totalPrice, cart, userInfo } = ctx.request.body
  
  const newOrder = {
    id: `order_${Date.now()}_${Math.floor(Math.random() * 1000)}`,
    status: 'pending',
    total_price: totalPrice,
    cart: typeof cart === 'string' ? cart : JSON.stringify(cart),
    user_info: typeof userInfo === 'string' ? userInfo : JSON.stringify(userInfo || {})
  }
  
  await query(
    'INSERT INTO orders (id, status, total_price, cart, user_info) VALUES (?, ?, ?, ?, ?)',
    [newOrder.id, newOrder.status, newOrder.total_price, newOrder.cart, newOrder.user_info]
  )
  
  ctx.body = {
    code: 200,
    data: newOrder
  }
}

async function updateOrder(ctx) {
  const orderId = ctx.params.id
  const updates = ctx.request.body
  
  const orders = await query('SELECT * FROM orders WHERE id = ?', [orderId])
  
  if (orders.length > 0) {
    const updateFields = []
    const updateParams = []
    
    if (updates.status !== undefined) {
      updateFields.push('status = ?')
      updateParams.push(updates.status)
    }
    if (updates.total_price !== undefined) {
      updateFields.push('total_price = ?')
      updateParams.push(updates.total_price)
    }
    if (updates.cart !== undefined) {
      updateFields.push('cart = ?')
      updateParams.push(typeof updates.cart === 'string' ? updates.cart : JSON.stringify(updates.cart))
    }
    
    updateParams.push(orderId)
    
    await query(`UPDATE orders SET ${updateFields.join(', ')} WHERE id = ?`, updateParams)
    
    const updatedOrders = await query('SELECT * FROM orders WHERE id = ?', [orderId])
    
    ctx.body = {
      code: 200,
      data: updatedOrders[0]
    }
  } else {
    ctx.body = {
      code: 404,
      message: '订单不存在'
    }
  }
}

module.exports = {
  getOrders,
  getOrderById,
  createOrder,
  updateOrder
}