// models/LandingPageModel/landingPageModel.js
module.exports = (sequelize, DataTypes) => {
  const LandingPage = sequelize.define(
    "LandingPage",
    {
      college_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
      },
      college_url: {
        type: DataTypes.STRING(255),
        defaultValue: "",
      },
      college_logo: {
        type: DataTypes.STRING(255),
        defaultValue: "",
      },
      college_banner: {
        type: DataTypes.STRING(500),
        defaultValue: "",
      },
      title_1: {
        type: DataTypes.STRING(255),
        defaultValue: "",
      },
      description_1: {
        type: DataTypes.TEXT("long"),
        defaultValue: "",
      },
      title_2: {
        type: DataTypes.STRING(255),
        defaultValue: "",
      },
      description_2: {
        type: DataTypes.TEXT("long"),
        defaultValue: "",
      },
      companies: {
        type: DataTypes.TEXT,
        defaultValue: "[]",
        get() {
          const rawValue = this.getDataValue("companies");
          try {
            return rawValue ? JSON.parse(rawValue) : [];
          } catch (e) {
            console.error("Error parsing companies JSON:", e);
            return [];
          }
        },
        set(value) {
          if (Array.isArray(value)) {
            this.setDataValue("companies", JSON.stringify(value));
          } else if (typeof value === "string") {
            try {
              JSON.parse(value);
              this.setDataValue("companies", value);
            } catch (e) {
              console.error("Invalid companies JSON string:", e);
              this.setDataValue("companies", "[]");
            }
          } else {
            this.setDataValue("companies", "[]");
          }
        },
      },
      datetime: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
      },
    },
    {
      tableName: "landing_pages",
      timestamps: false,
      underscored: true,
    }
  );

  LandingPage.associate = (models) => {
    LandingPage.belongsTo(models.College, {
      foreignKey: "college_id",
      as: "college",
    });
  };

  return LandingPage;
};
