"use strict";
const { DataTypes } = require("sequelize");

module.exports = (sequelize) => {
  const SignalSubscription = sequelize.define(
    "SignalSubscription",
    {
      id: {
        type: DataTypes.BIGINT.UNSIGNED,
        autoIncrement: true,
        primaryKey: true,
        allowNull: false,
      },

      userId: { type: DataTypes.BIGINT.UNSIGNED, allowNull: false, field: "user_id" },
      providerId: { type: DataTypes.BIGINT.UNSIGNED, allowNull: false, field: "provider_id" },

      status: {
        type: DataTypes.ENUM("active", "cancelled", "paused", "stopped", "expired", "suspended"),
        defaultValue: "active",
      },

      startDate: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW, field: "start_date" },
      endDate: { type: DataTypes.DATE, field: "end_date" },

      autoRenew: { type: DataTypes.BOOLEAN, defaultValue: true, field: "auto_renew" },

      price: { type: DataTypes.DECIMAL(10, 2), allowNull: false },
      pricePeriod: {
        type: DataTypes.ENUM("month", "year", "lifetime"),
        defaultValue: "month",
        field: "price_period",
      },

      lastPaymentDate: { type: DataTypes.DATE, field: "last_payment_date" },
      nextPaymentDate: { type: DataTypes.DATE, field: "next_payment_date" },

      notificationsEnabled: { type: DataTypes.BOOLEAN, defaultValue: true, field: "notifications_enabled" },

      autoCopyEnabled: { type: DataTypes.BOOLEAN, defaultValue: false, field: "auto_copy_enabled" },
      autoCopyConfig: { type: DataTypes.JSON, field: "auto_copy_config" },

      signalsTaken: { type: DataTypes.INTEGER.UNSIGNED, defaultValue: 0, field: "signals_taken" },

      profitLoss: { type: DataTypes.DECIMAL(20, 8), defaultValue: 0, field: "profit_loss" },

      rating: { type: DataTypes.INTEGER },
      review: { type: DataTypes.TEXT },
      reviewedAt: { type: DataTypes.DATE, field: "reviewed_at" },
    },
    {
      tableName: "signal_subscriptions",
      underscored: true,
      timestamps: true,
      indexes: [
        { fields: ["user_id"] },
        { fields: ["provider_id"] },
        { fields: ["status"] },
        { unique: true, fields: ["user_id", "provider_id"] },
      ],
    }
  );

  SignalSubscription.associate = (models) => {
    SignalSubscription.belongsTo(models.SignalProvider, {
      foreignKey: "providerId",
      as: "provider",
    });

    SignalSubscription.belongsTo(models.User, {
      foreignKey: "userId",
      as: "user",
    });
  };

  return SignalSubscription;
};