import mongoose from "mongoose"
import type { PluginFastifyInstance } from "types"
import { v4 as uuidv4 } from "uuid"
const { Schema } = mongoose

export const MODEL_BASENAME = "composition"

// TODO: in progress
const widgetSchema = new Schema(
  {
    uuid: {
      type: String,
      required: true,
    },
    name: {
      type: String,
      required: true,
    },
    pluginKey: {
      type: String,
      required: true,
    },
    config: {
      type: Object,
      required: false,
    },
    public: {
      type: Object,
      required: false,
    },
  },
  { _id: false },
)

// TODO: in progress
const widgetLayoutSchema = new Schema(
  {
    column: {
      type: Number,
      required: true,
    },
    widget: {
      type: widgetSchema,
      required: true,
    },
  },
  { _id: false },
)

const compositionSchema = new Schema(
  {
    _id: {
      type: String,
      default: () => uuidv4(),
      required: true,
    },

    title: {
      type: String,
      required: true,
      maxLength: 200,
    },

    description: {
      type: String,
      required: false,
    },

    tags: [
      {
        type: Schema.Types.String,
        ref: "raclette__core-tag",
      },
    ],

    icon: {
      type: String,
    },

    pathname: {
      type: Map,
      of: String,
      default: new Map(),
    },

    slotLayout: {
      type: String,
      default: "default",
    },

    widgetsLayout: {
      // TODO: in progress
      type: [[widgetLayoutSchema]],
      default: [],
    },

    status: {
      type: String,
      enum: ["live", "test", "inProgress"],
      default: "inProgress",
    },

    author: {
      type: Schema.Types.String,
      ref: "raclette__core-user",
      required: true,
    },

    lastEditor: {
      type: Schema.Types.String,
      ref: "raclette__core-user",
      required: true,
    },

    isDeleted: { type: Boolean, default: false },
  },
  { timestamps: true },
)

export const createModels = (fastify: PluginFastifyInstance) => {
  return fastify.createModel(MODEL_BASENAME, compositionSchema)
}
