/* eslint-disable @typescript-eslint/lines-between-class-members */
import { CreationOptional, DataTypes, InferAttributes, InferCreationAttributes, Model } from 'sequelize';

import { createIdGenerator } from '../../libs/util';

export const nextEntitlementId = createIdGenerator('ent', 24);

// eslint-disable-next-line prettier/prettier
export class Entitlement extends Model<InferAttributes<Entitlement>, InferCreationAttributes<Entitlement>> {
  declare id: CreationOptional<string>;
  declare livemode: boolean;

  declare key: string;
  declare name?: string;
  declare description?: string;

  declare metadata?: Record<string, any>;

  declare created_at: CreationOptional<Date>;
  declare updated_at: CreationOptional<Date>;

  public static readonly GENESIS_ATTRIBUTES = {
    id: {
      type: DataTypes.STRING(30),
      primaryKey: true,
      allowNull: false,
      defaultValue: nextEntitlementId,
    },
    livemode: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
    },
    key: {
      type: DataTypes.STRING(64),
      allowNull: false,
      unique: true,
    },
    name: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    metadata: {
      type: DataTypes.JSON,
      allowNull: true,
    },
    created_at: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      allowNull: false,
    },
    updated_at: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      allowNull: false,
    },
  };

  public static initialize(sequelize: any) {
    this.init(Entitlement.GENESIS_ATTRIBUTES, {
      sequelize,
      modelName: 'Entitlement',
      tableName: 'entitlements',
      createdAt: 'created_at',
      updatedAt: 'updated_at',
    });
  }

  public static associate(models: any) {
    this.belongsToMany(models.Product, {
      through: models.EntitlementProduct,
      foreignKey: 'entitlement_id',
      otherKey: 'product_id',
      as: 'products',
    });
    this.hasMany(models.EntitlementGrant, {
      foreignKey: 'entitlement_id',
      as: 'grants',
    });
  }
}

export type TEntitlement = InferAttributes<Entitlement>;
