import { CreationOptional, DataTypes, InferAttributes, InferCreationAttributes, Model } from 'sequelize';
import type { LiteralUnion } from 'type-fest';

import { createIdGenerator } from '../../libs/util';
import type { EventType } from './types';

const nextId = createIdGenerator('we', 24);

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

  declare url: string;
  declare description: string;
  declare enabled_events: EventType[];

  declare metadata: Record<string, any>;

  declare status: LiteralUnion<'enabled' | 'disabled', string>;

  declare created_at: CreationOptional<Date>;
  declare created_via: LiteralUnion<'api' | 'dashboard' | 'portal', string>;
  declare updated_at: CreationOptional<Date>;

  public static readonly GENESIS_ATTRIBUTES = {
    id: {
      type: DataTypes.STRING(30),
      primaryKey: true,
      allowNull: false,
      defaultValue: nextId,
    },
    livemode: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
    },
    api_version: {
      type: DataTypes.STRING(16),
      allowNull: false,
    },
    url: {
      type: DataTypes.STRING(512),
      allowNull: false,
    },
    description: {
      type: DataTypes.STRING(512),
      allowNull: true,
    },
    enabled_events: {
      type: DataTypes.JSON,
      allowNull: false,
    },
    metadata: {
      type: DataTypes.JSON,
      allowNull: true,
    },
    status: {
      type: DataTypes.ENUM('enabled', 'disabled'),
      allowNull: false,
    },
    created_at: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      allowNull: false,
    },
    created_via: {
      type: DataTypes.ENUM('api', 'dashboard', 'portal'),
    },
    updated_at: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      allowNull: false,
    },
  };

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

  public static associate(models: any) {
    this.hasMany(models.WebhookAttempt, {
      sourceKey: 'id',
      foreignKey: 'webhook_endpoint_id',
      as: 'attempts',
    });
  }
}

export type TWebhookEndpoint = InferAttributes<WebhookEndpoint>;
