import mongoConnection from "$connections/mongo/mongo.connection.js";

import mongoose from "mongoose";
const mongooseSchema = mongoose.Schema;

export const MESSAGE_AUDIENCES = ["all", "roles"];
export const MESSAGE_CTA_TYPES = ["internal", "external"];

export const schemaModel = {
  title: {
    type: String,
    required: true,
    trim: true,
    index: true,
  },
  body: {
    type: String,
    required: true,
    trim: true,
  },
  cta: {
    label: {
      type: String,
      default: "",
      trim: true,
    },
    url: {
      type: String,
      default: "",
      trim: true,
    },
    type: {
      type: String,
      enum: MESSAGE_CTA_TYPES,
      default: "internal",
    },
    openInNewTab: {
      type: Boolean,
      default: false,
    },
  },
  image: {
    type: mongooseSchema.Types.ObjectId,
    ref: "File",
    default: null,
  },
  showInHome: {
    type: Boolean,
    default: false,
    index: true,
  },
  audienceType: {
    type: String,
    enum: MESSAGE_AUDIENCES,
    default: "all",
    index: true,
  },
  targetRoles: {
    type: [String],
    default: [],
    index: true,
  },
  isActive: {
    type: Boolean,
    default: true,
    index: true,
  },
  createdBy: {
    type: mongooseSchema.Types.ObjectId,
    ref: "User",
    required: true,
    index: true,
  },
};

export const schema = new mongooseSchema(schemaModel, { timestamps: true });

schema.index({ audienceType: 1, targetRoles: 1, isActive: 1 });
schema.index(
  { showInHome: 1 },
  { unique: true, partialFilterExpression: { showInHome: true } },
);

schema.pre("validate", function (next) {
  if (Array.isArray(this.targetRoles)) {
    this.targetRoles = this.targetRoles
      .map((role) => (typeof role === "string" ? role.trim() : ""))
      .filter(Boolean);
  }

  if (this.audienceType === "all") {
    this.targetRoles = [];
  }

  if (!this.cta?.label || !this.cta?.url) {
    this.cta = {
      label: "",
      url: "",
      type: this.cta?.type || "internal",
      openInNewTab: Boolean(this.cta?.openInNewTab),
    };
  }

  next();
});

export default mongoConnection.model("Message", schema);
