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

export interface QuestionnaireQuestionAttributes {
    id: string;
    questionnaireId: string;
    sectionName: string;
    questionText: string;
    inputType: string;
    options: any;
    isMandatory: boolean;
    weight: number;
    order: number;
}

export interface QuestionnaireQuestionInstance extends Model<QuestionnaireQuestionAttributes>, QuestionnaireQuestionAttributes { }

export default (sequelize: Sequelize) => {
    const QuestionnaireQuestion = sequelize.define<QuestionnaireQuestionInstance>('QuestionnaireQuestion', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        questionnaireId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'questionnaires',
                key: 'id'
            }
        },
        sectionName: {
            type: DataTypes.STRING,
            allowNull: false
        },
        questionText: {
            type: DataTypes.TEXT,
            allowNull: false
        },
        inputType: {
            type: DataTypes.STRING,
            allowNull: false
        },
        options: {
            type: DataTypes.JSON,
            allowNull: true
        },
        isMandatory: {
            type: DataTypes.BOOLEAN,
            defaultValue: true
        },
        weight: {
            type: DataTypes.DECIMAL(5, 2),
            defaultValue: 0,
            allowNull: false
        },
        order: {
            type: DataTypes.INTEGER,
            defaultValue: 0,
            allowNull: false
        }
    }, {
        tableName: 'questionnaire_questions',
        timestamps: true,
        updatedAt: false
    });

    (QuestionnaireQuestion as any).associate = (models: any) => {
        QuestionnaireQuestion.belongsTo(models.Questionnaire, { foreignKey: 'questionnaireId', as: 'questionnaire' });
        QuestionnaireQuestion.hasMany(models.QuestionnaireResponse, { foreignKey: 'questionId', as: 'responses' });
        QuestionnaireQuestion.hasMany(models.QuestionnaireOption, { foreignKey: 'questionId', as: 'questionOptions' });
    };

    return QuestionnaireQuestion;
};
