const mongoose = require('mongoose');
const BaseModel = require('./BaseModel');

// Define the Role schema
const roleSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    lowercase: true
  },
  description: {
    type: String,
    required: true
  },
  permissions: [{
    type: String
  }],
  status: {
    type: Boolean,
    default: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
}, {
  timestamps: true
});

class Role extends BaseModel {
  static get schema() {
    return roleSchema;
  }

  static async getRoleByName(name) {
    return this.model.findOne({ name: name.toLowerCase() });
  }

  static async getRoleById(id) {
    return this.model.findById(id);
  }

  static async getRoles() {
    return this.model.find().sort({ createdAt: 1 });
  }

  static async initializeDefaultRoles() {
    const defaultRoles = [
      { 
        name: 'superadmin', 
        description: 'Super Administrator with full access', 
        permissions: ['*'] 
      },
      { 
        name: 'admin', 
        description: 'Administrator with full system access', 
        permissions: ['*'] 
      },
      { 
        name: 'store_manager', 
        description: 'Store Manager with store management access', 
        permissions: ['store.*', 'inventory.*', 'orders.*'] 
      },
      { 
        name: 'delivery_boy', 
        description: 'Delivery personnel', 
        permissions: ['delivery.*', 'orders.update'] 
      },
      { 
        name: 'customer', 
        description: 'Regular customer', 
        permissions: ['profile.*', 'orders.create', 'orders.view_own'] 
      }
    ];

    for (const role of defaultRoles) {
      const exists = await this.model.findOne({ name: role.name });
      if (!exists) {
        await this.model.create(role);
      } else {
        await this.model.findOneAndUpdate(
          { name: role.name },
          { $set: role },
          { new: true }
        );
      }
    }
  }
}

// Initialize the model
Role.init();

module.exports = Role;
