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

export class UserPreference extends Model<
  InferAttributes<UserPreference>,
  InferCreationAttributes<UserPreference>
> {
  declare id: CreationOptional<string>;
  declare userId: string;
  declare activeMode: CreationOptional<ActiveMode>;
  declare preferredLocale: CreationOptional<string | null>;
  declare timezone: CreationOptional<string | null>;
  declare notificationPreferences: CreationOptional<Record<
    string,
    unknown
  > | null>;
  declare createdAt: CreationOptional<Date>;
  declare updatedAt: CreationOptional<Date>;
}

export function initUserPreferenceModel(sequelize: Sequelize) {
  UserPreference.init(
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      userId: { type: DataTypes.UUID, allowNull: false, unique: true },
      activeMode: {
        type: DataTypes.ENUM("creator", "participant"),
        allowNull: false,
        defaultValue: "creator",
      },
      preferredLocale: { type: DataTypes.STRING(16), allowNull: true },
      timezone: { type: DataTypes.STRING(64), allowNull: true },
      notificationPreferences: {
        type: DataTypes.JSON,
        allowNull: true,
        get() {
          return parseJsonColumn<Record<string, unknown>>(
            this.getDataValue("notificationPreferences")
          );
        },
      },
      createdAt: DataTypes.DATE,
      updatedAt: DataTypes.DATE,
    },
    { sequelize, modelName: "UserPreference", tableName: "UserPreferences" }
  );
  return UserPreference;
}
