import {
  Sequelize,
  DataTypes,
  Model,
  InferAttributes,
  InferCreationAttributes,
  CreationOptional,
} from "sequelize";
import type {
  DomesticQuestionStatus,
  DomesticSensitivity,
} from "@/types/participant";

/** Stable identity (e.g. DOM-0180). Content lives in versions. */
export class DomesticQuestion extends Model<
  InferAttributes<DomesticQuestion>,
  InferCreationAttributes<DomesticQuestion>
> {
  declare id: CreationOptional<string>;
  declare code: string;
  declare categoryId: string;
  declare currentVersionId: CreationOptional<string | null>;
  declare status: CreationOptional<DomesticQuestionStatus>;
  declare sensitivity: CreationOptional<DomesticSensitivity>;
  /** Entry questions rotate into feeds; non-entry ones arrive only via edges. */
  declare isEntry: CreationOptional<boolean>;
  declare rotationWeight: CreationOptional<number>;
  declare createdBy: CreationOptional<string | null>;
  declare approvedBy: CreationOptional<string | null>;
  declare publishedAt: CreationOptional<Date | null>;
  declare createdAt: CreationOptional<Date>;
  declare updatedAt: CreationOptional<Date>;
}

export function initDomesticQuestionModel(sequelize: Sequelize) {
  DomesticQuestion.init(
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      code: { type: DataTypes.STRING(32), allowNull: false, unique: true },
      categoryId: { type: DataTypes.UUID, allowNull: false },
      currentVersionId: { type: DataTypes.UUID, allowNull: true },
      status: {
        type: DataTypes.ENUM("draft", "review", "published", "paused", "retired"),
        allowNull: false,
        defaultValue: "draft",
      },
      sensitivity: {
        type: DataTypes.ENUM("standard", "personal", "sensitive"),
        allowNull: false,
        defaultValue: "standard",
      },
      isEntry: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
      rotationWeight: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 100,
      },
      createdBy: { type: DataTypes.UUID, allowNull: true },
      approvedBy: { type: DataTypes.UUID, allowNull: true },
      publishedAt: { type: DataTypes.DATE, allowNull: true },
      createdAt: DataTypes.DATE,
      updatedAt: DataTypes.DATE,
    },
    {
      sequelize,
      modelName: "DomesticQuestion",
      tableName: "DomesticQuestions",
    }
  );
  return DomesticQuestion;
}
