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

export interface TaskWatcherAttributes {
  id: number;
  task_id: number;
  user_id: number;
  is_active: boolean;
}

interface TaskWatcherCreationAttributes extends Optional<TaskWatcherAttributes, 'id'> {}

export class TaskWatcher
  extends Model<TaskWatcherAttributes, TaskWatcherCreationAttributes>
  implements TaskWatcherAttributes {
  public id!: number;
  public task_id!: number;
  public user_id!: number;
  public is_active!: boolean;

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

  public static associate(models: any): void {
    TaskWatcher.belongsTo(models.Task, {
      foreignKey: 'task_id',
      as: 'task_watchers',
    });

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

  public toJSON(): TaskWatcherAttributes & {
    task?: TaskAttributes;
    user?: UserAttributes;
  } {
    return {
      ...super.toJSON(),
      id: this.id,
      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) => {
  TaskWatcher.init(
    {
      id: {
        type: dataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: 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: 'TaskWatcher',
      tableName: 'task_watchers',
      timestamps: true,
    }
  );

  return TaskWatcher;
};
