export default (sequelize, DataTypes) => {
  const KybApplication = sequelize.define("KybApplication", {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    merchantId: {
      type: DataTypes.UUID,
      allowNull: false,
      references: { model: "Merchants", key: "id" },
    },
    status: {
      type: DataTypes.ENUM(
        "Draft",
        "Submitted",
        "Under Review",
        "Additional Documents Required",
        "Approved",
        "Rejected"
      ),
      defaultValue: "Draft",
      allowNull: false,
    },
    companyName: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    diditSessionId: {
      type: DataTypes.STRING,
      allowNull: true,
      unique: true,
    },
    registrationNumber: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    companyAddress: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    companyType: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    businessDescription: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    website: {
      type: DataTypes.STRING,
      allowNull: true,
      validate: { isUrl: true },
    },
    incorporationDate: {
      type: DataTypes.DATEONLY,
      allowNull: true,
    },
    taxId: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    verificationOutcome: {
      type: DataTypes.JSON,
      allowNull: true,
      comment: "Results of third-party checks or automated screening",
    },
    rejectionReason: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    contactPersonName: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    companyPhone: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    companyEmail: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    natureOfBusiness: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    isLicensed: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
      allowNull: false,
    },
    licenseDocumentUrl: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    expectedMonthlyVolume: {
      type: DataTypes.STRING,
      allowNull: true,
    },
  }, {
    tableName: "KybApplications",
    timestamps: true,
  });

  KybApplication.associate = (models) => {
    KybApplication.belongsTo(models.Merchant, {
      foreignKey: "merchantId",
      as: "merchant",
    });
    KybApplication.hasMany(models.KybDocument, {
      foreignKey: "applicationId",
      as: "documents",
    });
    KybApplication.hasMany(models.KybDirector, {
      foreignKey: "applicationId",
      as: "directors",
    });
    KybApplication.hasMany(models.KybHistory, {
      foreignKey: "applicationId",
      as: "historyLogs",
    });
  };

  return KybApplication;
};
