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

export class Respondent extends Model<
  InferAttributes<Respondent>,
  InferCreationAttributes<Respondent>
> {
  declare id: CreationOptional<string>;
  declare surveyId: string;
  declare collectorId: string | null;
  declare status: RespondentStatus;
  declare startedAt: Date;
  declare completedAt: Date | null;
  declare timeToCompleteSeconds: number | null;
  declare ipHash: string | null;
  declare userAgent: string | null;
  declare createdAt: CreationOptional<Date>;
  declare updatedAt: CreationOptional<Date>;
}

export function initRespondentModel(sequelize: Sequelize) {
  Respondent.init(
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      surveyId: { type: DataTypes.UUID, allowNull: false },
      collectorId: { type: DataTypes.UUID, allowNull: true },
      status: {
        type: DataTypes.ENUM("in_progress", "completed", "abandoned"),
        allowNull: false,
        defaultValue: "in_progress",
      },
      startedAt: { type: DataTypes.DATE, allowNull: false },
      completedAt: { type: DataTypes.DATE, allowNull: true },
      timeToCompleteSeconds: {
        type: DataTypes.INTEGER.UNSIGNED,
        allowNull: true,
      },
      ipHash: { type: DataTypes.STRING(64), allowNull: true },
      userAgent: { type: DataTypes.STRING(512), allowNull: true },
      createdAt: DataTypes.DATE,
      updatedAt: DataTypes.DATE,
    },
    { sequelize, modelName: "Respondent", tableName: "Respondents" }
  );
  return Respondent;
}
