/**
 * Multi-tenant project context utilities
 * Handles extracting project slug from hostname and managing project context
 */

export interface ProjectContext {
  slug: string
  isMultiTenant: boolean
  hostname: string
}

/**
 * Known hostnames that should use local file system (not multi-tenant)
 */
const LOCAL_HOSTNAMES = [
  'localhost',
  '127.0.0.1',
  '0.0.0.0',
]

/**
 * The main platform domain
 */
const PLATFORM_DOMAIN = process.env.DEVDOC_PLATFORM_DOMAIN || 'devdoc.sh'

/**
 * Extract project context from hostname
 * 
 * Examples:
 * - my-docs.devdoc.sh -> { slug: 'my-docs', isMultiTenant: true }
 * - localhost:3000 -> { slug: null, isMultiTenant: false }
 * - docs.company.com -> { slug: lookup from custom domains, isMultiTenant: true }
 */
export function extractProjectContext(hostname: string): ProjectContext {
  // Remove port if present
  const host = hostname.split(':')[0]
  
  // Check if it's a local development hostname
  if (LOCAL_HOSTNAMES.includes(host)) {
    return {
      slug: '',
      isMultiTenant: false,
      hostname: host,
    }
  }
  
  // Check if it's a subdomain of the platform domain
  if (host.endsWith(`.${PLATFORM_DOMAIN}`)) {
    const slug = host.replace(`.${PLATFORM_DOMAIN}`, '')
    return {
      slug,
      isMultiTenant: true,
      hostname: host,
    }
  }
  
  // Check if it's the main platform domain
  if (host === PLATFORM_DOMAIN || host === `www.${PLATFORM_DOMAIN}`) {
    return {
      slug: '',
      isMultiTenant: false,
      hostname: host,
    }
  }
  
  // Custom domain - need to lookup in database
  // For now, return the full hostname as slug placeholder
  // This will be resolved via the domains API
  return {
    slug: host, // Will be resolved to actual slug via custom domains lookup
    isMultiTenant: true,
    hostname: host,
  }
}

/**
 * Check if running in multi-tenant mode
 */
export function isMultiTenantMode(): boolean {
  return process.env.MULTI_TENANT_MODE === 'true'
}

/**
 * Get the current project slug from environment or context
 */
export function getCurrentProjectSlug(): string | null {
  return process.env.DEVDOC_PROJECT_SLUG || null
}

/**
 * Build the URL for a project's docs
 */
export function getProjectUrl(slug: string): string {
  const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http'
  return `${protocol}://${slug}.${PLATFORM_DOMAIN}`
}

/**
 * Validate a project slug format
 */
export function isValidSlug(slug: string): boolean {
  // Must be lowercase alphanumeric with hyphens, 3-50 chars
  const slugRegex = /^[a-z0-9][a-z0-9-]{1,48}[a-z0-9]$/
  return slugRegex.test(slug)
}
