import {
  CreationOptional,
  DataTypes,
  InferAttributes,
  InferCreationAttributes,
  Model,
  Op,
  Sequelize,
} from "sequelize";

export type ArticleTranslationCreationAttributes =
  InferCreationAttributes<ArticleTranslation_Model>;

export class ArticleTranslation_Model extends Model<
  InferAttributes<ArticleTranslation_Model>,
  InferCreationAttributes<ArticleTranslation_Model>
> {
  // To avoid table creation
  /*static async sync(): Promise<any> {
    return Promise.resolve();
  }*/

  static associate(connection: Sequelize) {
    const { Article_Model, ArticleTranslation_Model } = connection.models;

    ArticleTranslation_Model.belongsTo(Article_Model, {
      as: "translations",
      foreignKey: "catalog_id",
      onDelete: "CASCADE",
    });
  }

  declare id: string;

  declare lang_code: CreationOptional<string>;
  declare description: CreationOptional<string>;
}

export default (sequelize: Sequelize) => {
  ArticleTranslation_Model.init(
    {
      id: {
        type: new DataTypes.UUID(),
        primaryKey: true,
      },

      lang_code: {
        type: DataTypes.STRING(2),
        allowNull: false,
        defaultValue: "es",
      },

      description: DataTypes.STRING(),
    },
    {
      sequelize,
      tableName: "catalog_translations",

      //paranoid: true, // softs deletes
      timestamps: false,
      //version: true,

      indexes: [{ name: "lang_code_idx", fields: ["lang_code"] }],

      whereMergeStrategy: "and", // <- cómo tratar el merge de un scope
      scopes: {
        quickSearch(value) {
          return {
            where: {
              [Op.or]: {
                description: {
                  [Op.like]: `%${value}%`,
                },
              },
            },
          };
        },
      },
    }
  );

  return ArticleTranslation_Model;
};
