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

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

export const schemaModel = {
  resource: {
    type: String,
    required: true,
    trim: true,
    // e.g., "users", "vouchers", "services"
  },
  resourceLabel: {
    type: String,
    required: true,
    trim: true,
    // Persian label for the resource: "کاربران", "کدهای تخفیف"
  },
  action: {
    type: String,
    required: true,
    enum: ["view", "create", "update", "delete"],
  },
  key: {
    type: String,
    required: true,
    unique: true,
    // Format: "users:view", "vouchers:delete"
  },
  label: {
    type: String,
    required: true,
    // Persian label: "مشاهده کاربران"
  },
  description: {
    type: String,
    default: "",
    // Detailed explanation for admins
  },
  isActive: {
    type: Boolean,
    default: true,
    // Soft disable permissions without deleting
  },
  isDangerous: {
    type: Boolean,
    default: false,
    // Mark high-risk operations (delete, etc.)
  },
};

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

// Auto-generate key from resource and action before save
schema.pre("save", function (next) {
  if (!this.key || this.isModified("resource") || this.isModified("action")) {
    this.key = `${this.resource}:${this.action}`;
  }
  next();
});

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