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

export type ArticleCreationAttributes = InferCreationAttributes<Article_Model>;

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

  static associate(connection: Sequelize) {}

  declare id: string;

  declare catalog_name: string;
  declare id_article: string; // number ??
  declare reference: CreationOptional<string>;
  declare lang_code: CreationOptional<string>;
  declare description: CreationOptional<string>;
  declare points: CreationOptional<number>;
  declare retail_price: CreationOptional<number>;
}

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

      catalog_name: {
        type: DataTypes.STRING(),
        allowNull: false,
      },

      id_article: {
        type: DataTypes.BIGINT().UNSIGNED,
        allowNull: false,
      },

      reference: DataTypes.STRING(),

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

      description: DataTypes.STRING(),

      points: {
        type: DataTypes.BIGINT().UNSIGNED,
        defaultValue: 0,
      },

      retail_price: DataTypes.BIGINT(),
    },
    {
      sequelize,
      tableName: "v_catalog",

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

      whereMergeStrategy: "and", // <- cómo tratar el merge de un scope

      defaultScope: {
        order: [["description", "ASC"]],
      },

      scopes: {
        quickSearch(values: string[]) {
          /**           
           * {
              [Op.or]: [
                { description: { [Op.like]: '%apple%' } },
                { description: { [Op.like]: '%banana%' } }
              ]
            }
            */

          return {
            where: {
              [Op.and]: values
                .map((value) => [{ description: { [Op.like]: `%${value}%` } }])
                .flat(),
            },
            order: [["description", "ASC"]],
          };
        },
      },
    }
  );

  return Article_Model;
};
