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

export interface SeaQACommentAttributes extends SeaQACommentInterface {}
export interface SeaQACommentCreationAttributes extends Optional<SeaQACommentAttributes, 'id' | 'parentId'> {}

export class SeaQAComment extends Model<SeaQACommentAttributes, SeaQACommentCreationAttributes> implements SeaQACommentAttributes {
    public id!: number;
    public answerId!: number;
    public userId!: number;
    public content!: string;
    public parentId!: number | null;
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;
    public readonly deletedAt!: Date | null;

    static initModel(sequelize: Sequelize): typeof SeaQAComment {
        SeaQAComment.init({
            id: { type: DataTypes.BIGINT, autoIncrement: true, primaryKey: true, comment: "unique identifier" },
            answerId: { type: DataTypes.BIGINT, allowNull: false, comment: "answer reference" },
            userId: { type: DataTypes.BIGINT, allowNull: false, comment: "author reference" },
            content: { type: DataTypes.TEXT, allowNull: false, comment: "comment content" },
            parentId: { type: DataTypes.BIGINT, allowNull: true, defaultValue: null, comment: "parent comment reference" }
        }, {
            sequelize,
            tableName: 'sea_qa_comments',
            timestamps: true,
            paranoid: true,
            underscored: true,
            indexes: [
                { name: 'sea_qa_comment_answer_index', fields: ['answer_id'] },
                { name: 'sea_qa_comment_parent_index', fields: ['parent_id'] }
            ]
        });
        return SeaQAComment;
    }

    public static associate(models: any) {
        SeaQAComment.belongsTo(models.SeaQAAnswer, { foreignKey: 'answerId', as: 'answer' });
        SeaQAComment.belongsTo(models.User, { foreignKey: 'userId', as: 'author' });
        SeaQAComment.belongsTo(models.SeaQAComment, { foreignKey: 'parentId', as: 'parent' });
        SeaQAComment.hasMany(models.SeaQAComment, { foreignKey: 'parentId', as: 'replies' });
    }
}
