import mongoose, { Schema, Document, Model } from "mongoose";
import { CalendarEvent } from "@calchat/shared";
import { IdVirtual } from "./types";

export interface EventDocument extends Omit<CalendarEvent, "id">, Document {
  toJSON(): CalendarEvent;
}

const EventSchema = new Schema<
  EventDocument,
  Model<EventDocument, {}, {}, IdVirtual>,
  {},
  {},
  IdVirtual
>(
  {
    userId: {
      type: String,
      required: true,
      index: true,
    },
    caldavUUID: {
      type: String,
    },
    etag: {
      type: String,
    },
    title: {
      type: String,
      required: true,
      trim: true,
    },
    description: {
      type: String,
      trim: true,
    },
    startTime: {
      type: Date,
      required: true,
    },
    endTime: {
      type: Date,
      required: true,
    },
    note: {
      type: String,
    },
    recurrenceRule: {
      type: String,
    },
    exceptionDates: {
      type: [String],
      default: [],
    },
  },
  {
    timestamps: true,
    virtuals: {
      id: {
        get() {
          return this._id.toString();
        },
      },
    },
    toJSON: {
      virtuals: true,
      transform: (_, ret: Record<string, unknown>) => {
        delete ret._id;
        delete ret.__v;
        return ret;
      },
    },
  },
);

EventSchema.index({ userId: 1, startTime: 1, endTime: 1 });

export const EventModel = mongoose.model<EventDocument>("Event", EventSchema);
