const Parse = require('parse/node');

// 加载所有 Schema 定义
const UserSchema = require('./schemas/User');
const ProductSchema = require('./schemas/Product');
const OrderSchema = require('./schemas/Order');
const OrderItemSchema = require('./schemas/OrderItem');
const PriceHistorySchema = require('./schemas/PriceHistory');

// 注册子类
Parse.Object.registerSubclass('Product', class extends Parse.Object {
  constructor(attributes) {
    super('Product', attributes);
  }
});

Parse.Object.registerSubclass('Order', class extends Parse.Object {
  constructor(attributes) {
    super('Order', attributes);
  }
});

// 其他类类似注册...

// 自动生成 Schema（开发环境）
if (process.env.NODE_ENV === 'development') {
  const schemas = [
    ProductSchema,
    OrderSchema,
    OrderItemSchema,
    PriceHistorySchema
  ];
  
  schemas.forEach(schema => {
    const parseSchema = new Parse.Schema(schema.className);
    
    Object.entries(schema.fields).forEach(([field, config]) => {
      parseSchema.addField(field, config.type, config);
    });
    
    parseSchema.save();
  });
}

// 添加业务逻辑钩子
Parse.Cloud.beforeSave('Order', async (request) => {
  const order = request.object;
  if (!order.get('orderNumber')) {
    // 生成唯一订单号
    order.set('orderNumber', `ORD-${Date.now()}-${Math.floor(Math.random()*1000)}`);
  }
});

Parse.Cloud.afterSave('OrderItem', async (request) => {
  // 更新订单总金额
  const order = request.object.get('order');
  const items = await new Parse.Query('OrderItem')
    .equalTo('order', order)
    .find();
  
  const total = items.reduce((sum, item) => 
    sum + (item.get('unitPrice') * item.get('quantity')), 0);
  
  order.set('totalAmount', total);
  await order.save();
});