// models/Tenant.js
// Tenant model definition

class Tenant {
  constructor(id, name, subdomain, settings, createdAt, updatedAt) {
    this.id = id;
    this.name = name;
    this.subdomain = subdomain;
    this.settings = settings || {};
    this.createdAt = createdAt || new Date();
    this.updatedAt = updatedAt || new Date();
  }

  // Static method to create a new tenant
  static create(tenantData) {
    const id = tenantData.id || require('uuid').v4();
    return new Tenant(
      id,
      tenantData.name,
      tenantData.subdomain,
      tenantData.settings
    );
  }

  // Method to validate a tenant
  validate() {
    if (!this.name || !this.subdomain) {
      throw new Error('Tenant name and subdomain are required');
    }
    
    // Validate subdomain format (alphanumeric and hyphens only)
    const subdomainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$/;
    if (!subdomainRegex.test(this.subdomain)) {
      throw new Error('Invalid subdomain format');
    }
    
    return true;
  }
}

module.exports = Tenant;