/**
 * Role Model
 *
 * Defines named sets of permissions for Role-Based Access Control (RBAC).
 * Five default roles are seeded on startup.
 * The super-admin role is marked isSystem: true and cannot be modified or deleted.
 *
 * Roles are scoped: `scope: 'global'` means platform-wide (visible to all orgs),
 * `scope: '<companyId>'` means org-scoped (visible only within that organization).
 */

import mongoose, { Schema, Document } from 'mongoose';

// --- Permission sub-schema ---

export interface IPermission {
  module: string;        // Matches ModuleDefinition.id from frontend modules.ts
  page?: string;         // Optional sub-page (e.g., 'strategy', 'assets')
  feature?: string;      // Optional feature within a module
  actions: string[];     // ['view','create','edit','delete','ai-generate','export','manage',...]
}

const PermissionSchema = new Schema<IPermission>({
  module: { type: String, required: true, trim: true },
  page: { type: String, trim: true },
  feature: { type: String, trim: true },
  actions: [{ type: String, trim: true }],
}, { _id: false });

// --- Role schema ---

export interface IRole extends Document {
  name: string;
  displayName: string;
  description?: string;
  isDefault: boolean;
  isOrgDefault: boolean;
  isSystem: boolean;
  isActive: boolean;
  scope: string;            // 'global' or a companyId
  permissions: IPermission[];
  createdAt: Date;
  updatedAt: Date;
}

const RoleSchema = new Schema<IRole>({
  name: {
    type: String,
    required: [true, 'Role name is required'],
    trim: true,
    lowercase: true,
    maxlength: [50, 'Role name cannot exceed 50 characters'],
  },
  displayName: {
    type: String,
    required: [true, 'Display name is required'],
    trim: true,
    maxlength: [100, 'Display name cannot exceed 100 characters'],
  },
  description: {
    type: String,
    trim: true,
    maxlength: [500, 'Description cannot exceed 500 characters'],
  },
  isDefault: {
    type: Boolean,
    default: false,
  },
  isOrgDefault: {
    type: Boolean,
    default: false,
  },
  isSystem: {
    type: Boolean,
    default: false,
  },
  isActive: {
    type: Boolean,
    default: true,
  },
  scope: {
    type: String,
    default: 'global',
  },
  permissions: [PermissionSchema],
}, {
  timestamps: true,
});

// Indexes — compound unique on name+scope, allowing same name in different org scopes
RoleSchema.index({ name: 1, scope: 1 }, { unique: true });
RoleSchema.index({ isDefault: 1 });
RoleSchema.index({ isActive: 1 });
RoleSchema.index({ scope: 1 });

export const Role = mongoose.models.Role || mongoose.model<IRole>('Role', RoleSchema);