const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

/**
 * PaymentOrder Model
 * Represents offline payment orders created by admin
 */
const PaymentOrder = sequelize.define('PaymentOrder', {
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true,
  },
  orderNo: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    field: 'order_no',
    comment: '订单编号，自动生成',
  },
  userId: {
    type: DataTypes.UUID,
    allowNull: false,
    field: 'user_id',
    references: {
      model: 'user',
      key: 'id',
    },
    comment: '支付用户ID',
  },
  appointmentId: {
    type: DataTypes.UUID,
    allowNull: true,
    field: 'appointment_id',
    references: {
      model: 'appointment',
      key: 'id',
    },
    comment: '关联预约单ID（可选）',
  },
  amount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true,
    defaultValue: null,
    comment: '支付金额（人民币，保留用于兼容）',
  },
  amountPeso: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true,
    defaultValue: null,
    field: 'amount_peso',
    comment: '支付金额（比索）',
  },
  amountRmb: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true,
    defaultValue: null,
    field: 'amount_rmb',
    comment: '支付金额（人民币）',
  },
  serviceContent: {
    type: DataTypes.TEXT,
    allowNull: false,
    field: 'service_content',
    comment: '服务内容',
  },
  paymentTime: {
    type: DataTypes.DATE,
    allowNull: false,
    field: 'payment_time',
    comment: '下单时间',
  },
  notes: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '备注（可选）',
  },
  createdBy: {
    type: DataTypes.UUID,
    allowNull: false,
    field: 'created_by',
    references: {
      model: 'admin',
      key: 'id',
    },
    comment: '创建人（管理员ID）',
  },
  status: {
    type: DataTypes.ENUM('active', 'cancelled'),
    defaultValue: 'active',
    allowNull: false,
    comment: '订单状态',
  },
  cancelReason: {
    type: DataTypes.TEXT,
    allowNull: true,
    field: 'cancel_reason',
    comment: '取消原因',
  },
}, {
  tableName: 'payment_orders',
  timestamps: true,
  underscored: true,
  indexes: [
    { fields: ['order_no'], unique: true },
    { fields: ['user_id'] },
    { fields: ['appointment_id'] },
    { fields: ['status'] },
    { fields: ['payment_time'] },
    { fields: ['created_by'] },
  ],
});

module.exports = PaymentOrder;
