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

export class VotingEntity extends Model<
  InferAttributes<VotingEntity>,
  InferCreationAttributes<VotingEntity>
> {
  declare id: CreationOptional<string>;
  declare workspaceId: string;
  declare entityType: VotingEntityType;
  declare label: string;
  declare metadata: Record<string, unknown> | null;
  declare isActive: CreationOptional<boolean>;
  declare createdAt: CreationOptional<Date>;
  declare updatedAt: CreationOptional<Date>;
}

export function initVotingEntityModel(sequelize: Sequelize) {
  VotingEntity.init(
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      workspaceId: { type: DataTypes.UUID, allowNull: false },
      entityType: {
        type: DataTypes.ENUM(
          "individual",
          "property_unit",
          "shareholder_account",
          "membership",
          "custom"
        ),
        allowNull: false,
      },
      label: { type: DataTypes.STRING(255), allowNull: false },
      metadata: {
        type: DataTypes.JSON,
        allowNull: true,
        get() {
          return parseJsonColumn<Record<string, unknown>>(
            this.getDataValue("metadata")
          );
        },
        set(value: Record<string, unknown> | string | null) {
          this.setDataValue(
            "metadata",
            typeof value === "string"
              ? parseJsonColumn<Record<string, unknown>>(value)
              : value
          );
        },
      },
      isActive: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: true,
      },
      createdAt: DataTypes.DATE,
      updatedAt: DataTypes.DATE,
    },
    { sequelize, modelName: "VotingEntity", tableName: "VotingEntities" }
  );
  return VotingEntity;
}
