import { Sequelize, DataTypes, Model, Optional } from 'sequelize';
import { TaskAttributes } from './Task';
import { UserAttributes } from './User';

export interface TrackexNotificationAttributes {
  id: number;
  priority: boolean;
  type: string;
  title: string;
  text: string;
  task_id?: number;
  user_id: number;
  is_active: boolean;
  task?: TaskAttributes;
  user?: UserAttributes;
}

interface NotificationCreationAttributes
  extends Optional<TrackexNotificationAttributes, 'id'> {}

export class TrackexNotification
  extends Model<TrackexNotificationAttributes, NotificationCreationAttributes>
  implements TrackexNotificationAttributes {
  public id!: number;
  public priority!: boolean;
  public type!: string;
  public title!: string;
  public text!: string;
  public task_id?: number;
  public user_id!: number;
  public is_active!: boolean;

  public task?: TaskAttributes;
  public user?: UserAttributes;

  public static associate(models: any) {
    TrackexNotification.belongsTo(models.Task, {
      foreignKey: 'task_id',
      as: 'task'
    });

    TrackexNotification.belongsTo(models.User, {
      foreignKey: 'user_id',
      as: 'user'
    });
  }

  public toJSON(): TrackexNotificationAttributes {
    return {
      ...super.toJSON(),
      id: this.id,
      priority: this.priority,
      type: this.type,
      title: this.title,
      text: this.text,
      task_id: this.task_id,
      user_id: this.user_id,
      is_active: this.is_active,
      task: this.task,
      user: this.user
    };
  }
}

export default (sequelize: Sequelize, dataTypes: typeof DataTypes) => {
  TrackexNotification.init(
    {
      id: {
        type: dataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
      },
      priority: {
        type: dataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: false
      },
      type: {
        type: dataTypes.STRING,
        allowNull: true
      },
      title: {
        type: dataTypes.STRING,
        allowNull: true
      },
      text: {
        type: dataTypes.TEXT,
        allowNull: true
      },
      task_id: {
        type: dataTypes.INTEGER,
        allowNull: false,
        references: {
          model: 'tasks',
          key: 'id'
        },
      },
      user_id: {
        type: dataTypes.INTEGER,
        allowNull: false,
        references: {
          model: 'users',
          key: 'id'
        },
      },
      is_active: {
        type: dataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: true
      }
    },
    {
      sequelize,
      modelName: 'TrackexNotification',
      tableName: 'trackex_notifications',
      timestamps: true
    }
  );

  return TrackexNotification;
};
