import mongoose, { Model } from 'mongoose';

import { MODEL_NAMES } from './_models';

export type ScorecardAnswerValue =
  | boolean
  | number
  | string;

export interface IScorecardAnswer {
  submissionId: mongoose.Types.ObjectId;
  criterionKey: string;
  value: ScorecardAnswerValue;
  calculatedScore: number;
}

export interface IScorecardAnswerDoc extends IScorecardAnswer, Document {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IScorecardAnswerLean extends IScorecardAnswer {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IScorecardAnswerPlain extends Omit<IScorecardAnswer, 'submissionId'> {
  _id: string;
  submissionId: string;
}

export type TScorecardAnswerModel = Model<IScorecardAnswer>;

export const ScorecardAnswerSchema = new mongoose.Schema<IScorecardAnswer, TScorecardAnswerModel>(
  {
    submissionId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.scorecardSubmission,
      required: true,
    },
    criterionKey: {
      type: String,
      required: true,
    },
    value: {
      type: mongoose.Schema.Types.Mixed,
      required: true,
    },
    calculatedScore: {
      type: Number,
      required: true,
    },
  },
  {
    timestamps: { createdAt: true, updatedAt: true },
    versionKey: false,
  },
);

export const ScorecardAnswer = mongoose.model<IScorecardAnswer, TScorecardAnswerModel>(MODEL_NAMES.scorecardAnswer, ScorecardAnswerSchema);

ScorecardAnswerSchema.index(
  { submissionId: 1, criterionKey: 1 },
  { unique: true }
);
