export default (sequelize, DataTypes) => {
  const MerchantSubscription = sequelize.define("MerchantSubscription", {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    merchantId: {
      type: DataTypes.UUID,
      allowNull: false,
      references: { model: "Merchants", key: "id" },
    },
    planId: {
      type: DataTypes.UUID,
      allowNull: false,
      references: { model: "SubscriptionPlans", key: "id" },
    },
    status: {
      type: DataTypes.ENUM("active", "cancelled", "expired", "pending"),
      defaultValue: "active",
      allowNull: false,
    },
    startDate: {
      type: DataTypes.DATEONLY,
      allowNull: false,
    },
    endDate: {
      type: DataTypes.DATEONLY,
      allowNull: false,
    },
    autoRenew: {
      type: DataTypes.BOOLEAN,
      defaultValue: true,
    },
    cancelledAt: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: "When the merchant requested cancellation",
    },
    previousPlanId: {
      type: DataTypes.UUID,
      allowNull: true,
      references: { model: "SubscriptionPlans", key: "id" },
      comment: "Tracks upgrades/downgrades — the plan they switched from",
    },
  }, {
    tableName: "MerchantSubscriptions",
    timestamps: true,
  });

  MerchantSubscription.associate = (models) => {
    MerchantSubscription.belongsTo(models.Merchant, {
      foreignKey: "merchantId",
      as: "merchant",
    });
    MerchantSubscription.belongsTo(models.SubscriptionPlan, {
      foreignKey: "planId",
      as: "plan",
    });
    MerchantSubscription.belongsTo(models.SubscriptionPlan, {
      foreignKey: "previousPlanId",
      as: "previousPlan",
    });
    MerchantSubscription.hasMany(models.SubscriptionInvoice, {
      foreignKey: "subscriptionId",
      as: "invoices",
    });
  };

  return MerchantSubscription;
};
