import { Schema, model } from 'mongoose';
import { IRoleDoc, IRoleModel } from '@/modules/roles/roles.interface.js';
import { paginate, toJSON } from '@/shared/utils/plugins/index.js';

const roleSchema = new Schema<IRoleDoc>(
  {
    name: { type: String, required: true },
    description: { type: String },
    permissions: [{ type: Schema.Types.ObjectId, ref: 'Permission' }],
    parentRole: { type: Schema.Types.ObjectId, ref: 'Role' },
    createdBy: { type: Schema.Types.ObjectId, ref: 'User' },
    updatedBy: { type: Schema.Types.ObjectId, ref: 'User' },
    company: { type: Schema.Types.ObjectId, required: true, ref: 'Company' },
  },
  {
    timestamps: true,
  },
);

// add plugin that converts mongoose to json
roleSchema.plugin(toJSON);
roleSchema.plugin(paginate);

roleSchema.index(
  { company: 1, name: 1 },
  {
    unique: true,
    partialFilterExpression: {
      company: { $type: 'objectId' },
      name: { $type: 'string' },
    },
  },
);

export const Role = model<IRoleDoc, IRoleModel>('Role', roleSchema);
