import {
  Sequelize,
  DataTypes,
  Model,
  InferAttributes,
  InferCreationAttributes,
  CreationOptional,
} from "sequelize";
import { parseJsonColumn } from "@/lib/utils/parse-json-column";
import type {
  DomesticConditionConfig,
  DomesticConditionType,
  DomesticEdgeType,
} from "@/types/participant";

export class DomesticQuestionEdge extends Model<
  InferAttributes<DomesticQuestionEdge>,
  InferCreationAttributes<DomesticQuestionEdge>
> {
  declare id: CreationOptional<string>;
  declare fromQuestionVersionId: string;
  declare conditionType: DomesticConditionType;
  declare conditionConfig: CreationOptional<DomesticConditionConfig | null>;
  declare toQuestionId: CreationOptional<string | null>;
  declare priority: CreationOptional<number>;
  declare edgeType: CreationOptional<DomesticEdgeType>;
  declare effectiveFrom: Date;
  declare effectiveTo: CreationOptional<Date | null>;
  declare createdBy: CreationOptional<string | null>;
  declare createdAt: CreationOptional<Date>;
  declare updatedAt: CreationOptional<Date>;
}

export function initDomesticQuestionEdgeModel(sequelize: Sequelize) {
  DomesticQuestionEdge.init(
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      fromQuestionVersionId: { type: DataTypes.UUID, allowNull: false },
      conditionType: {
        type: DataTypes.ENUM(
          "always",
          "equals",
          "not_equals",
          "any_of",
          "includes",
          "gte",
          "lte"
        ),
        allowNull: false,
      },
      conditionConfig: {
        type: DataTypes.JSON,
        allowNull: true,
        get() {
          return parseJsonColumn<DomesticConditionConfig>(
            this.getDataValue("conditionConfig")
          );
        },
      },
      toQuestionId: { type: DataTypes.UUID, allowNull: true },
      priority: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 100 },
      edgeType: {
        type: DataTypes.ENUM("unlock", "boost", "suppress", "terminate"),
        allowNull: false,
        defaultValue: "unlock",
      },
      effectiveFrom: { type: DataTypes.DATE, allowNull: false },
      effectiveTo: { type: DataTypes.DATE, allowNull: true },
      createdBy: { type: DataTypes.UUID, allowNull: true },
      createdAt: DataTypes.DATE,
      updatedAt: DataTypes.DATE,
    },
    {
      sequelize,
      modelName: "DomesticQuestionEdge",
      tableName: "DomesticQuestionEdges",
    }
  );
  return DomesticQuestionEdge;
}
