import {
  Sequelize,
  DataTypes,
  Model,
  InferAttributes,
  InferCreationAttributes,
  CreationOptional,
} from "sequelize";
import type {
  QuestionType,
  QuestionOptionsConfig,
  QuestionValidationConfig,
} from "@/types";
import { parseJsonColumn } from "@/lib/utils/parse-json-column";

export class Question extends Model<
  InferAttributes<Question>,
  InferCreationAttributes<Question>
> {
  declare id: CreationOptional<string>;
  declare surveyId: string;
  declare type: QuestionType;
  declare title: string;
  declare position: CreationOptional<number>;
  declare isRequired: CreationOptional<boolean>;
  declare validationConfig: QuestionValidationConfig | null;
  declare optionsConfig: QuestionOptionsConfig | null;
  declare randomizeOptions: CreationOptional<boolean>;
  declare createdAt: CreationOptional<Date>;
  declare updatedAt: CreationOptional<Date>;
}

export function initQuestionModel(sequelize: Sequelize) {
  Question.init(
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      surveyId: { type: DataTypes.UUID, allowNull: false },
      type: {
        type: DataTypes.ENUM(
          "multiple_choice",
          "checkbox",
          "rating",
          "nps",
          "open_text",
          "matrix",
          "file_upload",
          "dropdown",
          "date_time"
        ),
        allowNull: false,
      },
      title: { type: DataTypes.TEXT, allowNull: false },
      position: {
        type: DataTypes.INTEGER.UNSIGNED,
        allowNull: false,
        defaultValue: 0,
      },
      isRequired: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: false,
      },
      validationConfig: {
        type: DataTypes.JSON,
        allowNull: true,
        get() {
          return parseJsonColumn<QuestionValidationConfig>(
            this.getDataValue("validationConfig")
          );
        },
      },
      optionsConfig: {
        type: DataTypes.JSON,
        allowNull: true,
        get() {
          return parseJsonColumn<QuestionOptionsConfig>(
            this.getDataValue("optionsConfig")
          );
        },
      },
      randomizeOptions: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: false,
      },
      createdAt: DataTypes.DATE,
      updatedAt: DataTypes.DATE,
    },
    { sequelize, modelName: "Question", tableName: "Questions" }
  );
  return Question;
}
