import { DataTypes, Model, Optional, Sequelize } from 'sequelize';

export interface CommentAttributes extends Optional<CommentInterface, 'id'> { }

export class Comment extends Model<CommentInterface, CommentAttributes> implements CommentInterface {
    public id!: number;
    public userId!: number | null;
    public postId!: number;
    public parentId!: number | null;
    public content!: Text | string;
    public status!: string;
    public commentAuthorName!: string | null;
    public commentAuthorEmail!: string | null;
    public wpCommentId!: number | null;
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;

    static initModel(sequelize: Sequelize): typeof Comment {
        Comment.init(
            {
                id: { type: DataTypes.BIGINT, autoIncrement: true, primaryKey: true, comment: "unique identifier" },
                userId: { type: DataTypes.BIGINT, allowNull: true, comment: "user identifier" },
                postId: { type: DataTypes.BIGINT, allowNull: false, comment: "post identifier" },
                parentId: { type: DataTypes.BIGINT, allowNull: true, defaultValue: null, comment: "parent comment identifier for replies" },
                content: { type: DataTypes.TEXT, allowNull: false, comment: "comment content" },
                status: { type: DataTypes.STRING, allowNull: false, defaultValue: 'pending', comment: "status: approved/pending/spam" },
                commentAuthorName: { type: DataTypes.STRING, allowNull: true, comment: "guest author name" },
                commentAuthorEmail: { type: DataTypes.STRING, allowNull: true, comment: "guest author email" },
                wpCommentId: { type: DataTypes.BIGINT, allowNull: true, comment: "original wordpress comment identifier" }
            },
            {
                paranoid: true,
                underscored: true,
                sequelize,
                tableName: 'comments',
                timestamps: true,
                indexes: [
                    { name: 'comment-post-index', fields: ['post_id'] },
                    { name: 'comment-parent-index', fields: ['parent_id'] },
                    { name: 'comment-status-index', fields: ['status'] }
                ]
            }
        );
        return Comment;
    }

    public static associate(models: any) {
        Comment.belongsTo(models.User, { foreignKey: 'userId', as: 'author' });
        Comment.belongsTo(models.Post, { foreignKey: 'postId', as: 'post' });
        Comment.belongsTo(models.Comment, { foreignKey: 'parentId', as: 'parent' });
        Comment.hasMany(models.Comment, { foreignKey: 'parentId', as: 'replies' });
    }
}
