import mongoose from "mongoose"
import { v4 as uuidv4 } from "uuid"
import { tagTypes } from "@shared/types/dataTypes/tags"
import { PluginFastifyInstance } from "types"
const { Schema } = mongoose

export const MODEL_BASENAME = "tag"

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

    /* tags can belong to a project or be global */
    project: {
      type: Schema.Types.String,
      ref: "raclette__core-project",
      required: false,
    },

    /* the actual tag content */
    title: {
      type: String,
      default: null,
      maxLength: 200,
    },
    /* tags, note that label and ticket have to belong to the same project */
    tags: {
      type: [Schema.Types.String],
      ref: "raclette__core-tag",
      default: [],
    },
    /* hex color code */
    color: {
      type: String,
      default: "#CCCCCC",
      validate: {
        validator: (value: string) => {
          const hexstring = /^#([0-9a-f]{3}){1,2}$/i
          return hexstring.test(value)
        },
        message: (props: any) => `${props.value} is not a valid hex value!`,
      },
    },

    owner: {
      type: Schema.Types.String,
      ref: "raclette__core-user",
      default: null,
    },

    updatedBy: {
      type: Schema.Types.String,
      ref: "raclette__core-user",
      default: null,
    },

    /* status, milestone, content, system */
    type: {
      type: String,
      maxLength: 50,
      default: "content",
      enum: tagTypes,
      required: true,
    },
    order: {
      type: Number,
      default: 0,
    },
    /* we want to discriminate project tags from simple user tags */
    locked: {
      type: Boolean,
      default: false,
    },

    /* soft delete */
    isDeleted: { type: Boolean, default: false },
  },
  { timestamps: true },
)

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