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

export class DigitalSignature extends Model<
  InferAttributes<DigitalSignature>,
  InferCreationAttributes<DigitalSignature>
> {
  declare id: CreationOptional<string>;
  declare ballotCastEventId: string | null;
  declare signerName: string;
  declare signatureType: DigitalSignatureType;
  declare signatureHash: string;
  declare ipAddress: string | null;
  declare dateStamp: string;
  declare timeStamp: Date;
  declare consentWithdrawnAt: Date | null;
  declare createdAt: CreationOptional<Date>;
  declare updatedAt: CreationOptional<Date>;
}

export function initDigitalSignatureModel(sequelize: Sequelize) {
  DigitalSignature.init(
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      ballotCastEventId: { type: DataTypes.UUID, allowNull: true },
      signerName: { type: DataTypes.STRING(255), allowNull: false },
      signatureType: {
        type: DataTypes.ENUM("typed", "drawn", "checkbox_consent"),
        allowNull: false,
        defaultValue: "checkbox_consent",
      },
      signatureHash: { type: DataTypes.STRING(128), allowNull: false },
      ipAddress: { type: DataTypes.STRING(64), allowNull: true },
      dateStamp: { type: DataTypes.DATEONLY, allowNull: false },
      timeStamp: { type: DataTypes.DATE, allowNull: false },
      consentWithdrawnAt: { type: DataTypes.DATE, allowNull: true },
      createdAt: DataTypes.DATE,
      updatedAt: DataTypes.DATE,
    },
    {
      sequelize,
      modelName: "DigitalSignature",
      tableName: "DigitalSignatures",
    }
  );
  return DigitalSignature;
}
