module.exports = function(sequelize, DataTypes) {
  const clients = sequelize.define(
    "clients",
    {
      id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
      name: { type: DataTypes.TEXT },
      email: { type: DataTypes.TEXT },
      status: { type: DataTypes.ENUM("lead", "active", "paused", "completed"), defaultValue: "active" },
      goals: { type: DataTypes.TEXT },
      notes: { type: DataTypes.TEXT },
      company: { type: DataTypes.TEXT },
      role_title: { type: DataTypes.TEXT },
      tags: { type: DataTypes.TEXT },
      next_session_at: { type: DataTypes.DATE },
      last_session_at: { type: DataTypes.DATE },
      portalUserId: { type: DataTypes.UUID },
      ai_processing_consent_granted: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },
      ai_processing_consent_at: { type: DataTypes.DATE },
      ai_processing_consent_policy_version: { type: DataTypes.TEXT },
      recording_consent_granted: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },
      recording_consent_at: { type: DataTypes.DATE },
      recording_consent_policy_version: { type: DataTypes.TEXT },
      consent_withdrawn_at: { type: DataTypes.DATE },
      consent_updated_by_id: { type: DataTypes.UUID },
      reminders_enabled: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
      reminder_minutes: { type: DataTypes.INTEGER },
      importHash: { type: DataTypes.STRING(255), allowNull: true, unique: true },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
    },
  );

  clients.associate = (db) => {
    db.clients.belongsTo(db.packages, { as: "package", foreignKey: { name: "packageId" }, constraints: false });
    db.clients.belongsTo(db.users, { as: "owner", foreignKey: { name: "ownerId" }, constraints: false });
    db.clients.belongsTo(db.users, { as: "portal_user", foreignKey: { name: "portalUserId" }, constraints: false });
    db.clients.hasMany(db.sessions, { as: "sessions", foreignKey: { name: "clientId" }, constraints: false });
    db.clients.hasMany(db.action_items, { as: "action_items", foreignKey: { name: "clientId" }, constraints: false });
    db.clients.hasMany(db.resources, { as: "resources", foreignKey: { name: "clientId" }, constraints: false });
    db.clients.hasMany(db.prep_briefs, { as: "prep_briefs", foreignKey: { name: "clientId" }, constraints: false });
    db.clients.belongsTo(db.users, { as: "createdBy", constraints: false });
    db.clients.belongsTo(db.users, { as: "updatedBy", constraints: false });
  };

  return clients;
};
