import mongoose from 'mongoose';

import { IUser } from '../interfaces/auth-user.interface';
import { MODEL_NAMES } from './_models';

export const REQUIRED_SIGNS = 2;

export interface IAvailabilitySignItem {
  userSignedId: string;
  signedAt: Date;
  userRevokedId?: string;
  revokedAt?: Date;
}

export interface IAvailabilitySignItemPreView {
  _id: mongoose.Types.ObjectId;
  userSignedId: string;
  signedAt: Date;
  userRevokedId?: string;
  revokedAt?: Date;
}

export interface IAvailabilitySignItemView {
  _id: mongoose.Types.ObjectId;
  userSigned: IUser;
  signedAt: Date;
  userRevoked?: IUser;
  revokedAt?: Date;
}

export interface IAvailabilitySign {
  bbcDateId: mongoose.Types.ObjectId;
  requiredSigns: number;
  signs: IAvailabilitySignItem[];
}

export interface IAvailabilitySignPreView {
  _id: mongoose.Types.ObjectId;
  bbcDateId: mongoose.Types.ObjectId;
  requiredSigns: number;
  signs: IAvailabilitySignItemPreView[];
}

export interface IAvailabilitySignView {
  _id: mongoose.Types.ObjectId;
  bbcDateId: mongoose.Types.ObjectId;
  requiredSigns: number;
  signs: IAvailabilitySignItemView[];
}

export interface IAvailabilitySignDoc extends IAvailabilitySign, mongoose.Document {
}

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

export interface IAvailabilitySignLean extends IAvailabilitySign {
  _id: mongoose.Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

export interface IAvailabilitySignPlain extends Omit<IAvailabilitySign, 'bbcDateId'> {
  _id: string;
  bbcDateId: string;
}

export type TAvailabilitySignModel = mongoose.Model<IAvailabilitySign>;

export const AvailabilitySignSchema = new mongoose.Schema(
  {
    bbcDateId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: MODEL_NAMES.BBCDates,
      required: true,
    },
    requiredSigns: {
      type: Number,
      required: true,
      default: REQUIRED_SIGNS,
    },
    signs: [
      {
        userSignedId: {
          type: String,
          required: true,
        },
        signedAt: {
          type: Date,
          required: true,
        },
        userRevokedId: {
          type: String,
          required: false,
        },
        revokedAt: {
          type: Date,
          required: false,
        },
      },
    ],
    __v: { type: Number, select: false },
  },
  { timestamps: true },
);

export const AvailabilitySignsModel = mongoose.model<IAvailabilitySignDoc>(MODEL_NAMES.availabilitySign, AvailabilitySignSchema);
