# ============================================================================
# Multi-Tenant SaaS SPARQL Queries
# ============================================================================
# Collection of SPARQL queries for multi-tenant SaaS operations
# Version: 1.0.0
# ============================================================================

PREFIX mt: <http://example.org/multi-tenant#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

# ============================================================================
# Query 1: Extract All Active Tenants with Subscription Tiers
# ============================================================================
# Returns: List of active tenants with their subscription details

SELECT ?tenantId ?tenantName ?tierLabel ?isolationStrategy
WHERE {
    ?tenant a mt:Tenant ;
            mt:tenantId ?tenantId ;
            mt:tenantName ?tenantName ;
            mt:hasLifecycleState mt:ActiveTenant ;
            mt:hasSubscriptionTier ?tier ;
            mt:hasIsolationStrategy ?strategy .

    ?tier rdfs:label ?tierLabel .
    ?strategy rdfs:label ?isolationStrategy .
}
ORDER BY ?tenantName

# ============================================================================
# Query 2: Generate Tenant Provisioning Schema (Schema Isolation)
# ============================================================================
# Returns: Schema creation statements for new tenant

SELECT ?tenantSlug ?schemaName ?isolationStrategy
WHERE {
    ?tenant mt:tenantSlug ?tenantSlug ;
            mt:hasIsolationStrategy mt:SchemaIsolation .

    BIND(CONCAT("tenant_", ?tenantSlug) AS ?schemaName)
    BIND("schema_isolation" AS ?isolationStrategy)
}

# ============================================================================
# Query 3: Calculate Usage Metrics per Tenant
# ============================================================================
# Returns: Aggregated usage metrics for billing

SELECT ?tenantId ?tenantName
       (SUM(?apiCalls) AS ?totalApiCalls)
       (SUM(?storage) AS ?totalStorage)
       (SUM(?compute) AS ?totalCompute)
WHERE {
    ?tenant mt:tenantId ?tenantId ;
            mt:tenantName ?tenantName ;
            mt:hasUsageMetric ?metric .

    OPTIONAL {
        ?metric a mt:ApiCallMetric ;
                mt:metricValue ?apiCalls .
    }
    OPTIONAL {
        ?metric a mt:StorageMetric ;
                mt:metricValue ?storage .
    }
    OPTIONAL {
        ?metric a mt:ComputeMetric ;
                mt:metricValue ?compute .
    }
}
GROUP BY ?tenantId ?tenantName
ORDER BY DESC(?totalApiCalls)

# ============================================================================
# Query 4: Generate Billing Records for Monthly Cycle
# ============================================================================
# Returns: Billing amounts based on usage and subscription tier

SELECT ?tenantId ?tierLabel ?basePrice
       (?basePrice + ?overage AS ?totalAmount)
WHERE {
    ?tenant mt:tenantId ?tenantId ;
            mt:hasSubscriptionTier ?tier ;
            mt:hasBillingCycle mt:MonthlyBilling .

    ?tier rdfs:label ?tierLabel .

    # Base pricing by tier
    BIND(
        IF(?tier = mt:FreeTier, 0,
        IF(?tier = mt:BasicTier, 29,
        IF(?tier = mt:ProTier, 99,
        IF(?tier = mt:EnterpriseTier, 499, 0))))
        AS ?basePrice
    )

    # Calculate overage charges
    BIND(0 AS ?overage)  # TODO: Calculate from quota usage
}

# ============================================================================
# Query 5: Check Quota Violations (Over Limit)
# ============================================================================
# Returns: Tenants exceeding their quotas

SELECT ?tenantId ?quotaType ?limit ?usage (?usage - ?limit AS ?overage)
WHERE {
    ?tenant mt:tenantId ?tenantId ;
            mt:hasQuota ?quota .

    ?quota a ?quotaType ;
           mt:quotaLimit ?limit ;
           mt:currentUsage ?usage .

    FILTER(?usage > ?limit)
}
ORDER BY DESC(?overage)

# ============================================================================
# Query 6: Extract Feature Flags by Tenant and Tier
# ============================================================================
# Returns: Feature enablement status per tenant

SELECT ?tenantId ?featureName ?isEnabled ?tierLabel
WHERE {
    ?tenant mt:tenantId ?tenantId ;
            mt:hasSubscriptionTier ?tier ;
            mt:hasFeatureFlag ?flag .

    ?flag mt:featureName ?featureName ;
          mt:isEnabled ?isEnabled .

    ?tier rdfs:label ?tierLabel .
}
ORDER BY ?tenantId ?featureName

# ============================================================================
# Query 7: Identify Suspended Tenants for Reactivation
# ============================================================================
# Returns: Suspended tenants with suspension reasons

SELECT ?tenantId ?tenantName ?suspendedAt ?daysInactive
WHERE {
    ?tenant mt:tenantId ?tenantId ;
            mt:tenantName ?tenantName ;
            mt:hasLifecycleState mt:SuspendedTenant ;
            mt:suspendedAt ?suspendedAt .

    BIND(NOW() AS ?now)
    BIND((?now - ?suspendedAt) / (60 * 60 * 24) AS ?daysInactive)
}
ORDER BY DESC(?daysInactive)

# ============================================================================
# Query 8: Generate Tenant Migration Plan
# ============================================================================
# Returns: Tenants requiring migration to different isolation strategy

SELECT ?tenantId ?currentStrategy ?targetStrategy ?dataSize
WHERE {
    ?tenant mt:tenantId ?tenantId ;
            mt:hasIsolationStrategy ?current ;
            mt:hasSubscriptionTier mt:EnterpriseTier .

    ?current rdfs:label ?currentStrategy .

    # Enterprise tenants should use DatabaseIsolation
    BIND(mt:DatabaseIsolation AS ?target)
    ?target rdfs:label ?targetStrategy .

    FILTER(?current != mt:DatabaseIsolation)

    BIND(1000000 AS ?dataSize)  # TODO: Calculate actual data size
}

# ============================================================================
# Query 9: Extract Data Residency and Compliance Requirements
# ============================================================================
# Returns: Geographic and regulatory requirements per tenant

SELECT ?tenantId ?region ?complianceStandard
WHERE {
    ?tenant mt:tenantId ?tenantId ;
            mt:hasDataResidency ?residency ;
            mt:hasComplianceRequirement ?compliance .

    ?residency mt:residencyRegion ?region .
    ?compliance mt:complianceStandard ?complianceStandard .
}

# ============================================================================
# Query 10: Calculate API Rate Limits by Tier
# ============================================================================
# Returns: Rate limits for API throttling

SELECT ?tenantId ?tierLabel ?rateLimitPerMinute
WHERE {
    ?tenant mt:tenantId ?tenantId ;
            mt:hasSubscriptionTier ?tier ;
            mt:hasQuota ?rateLimit .

    ?rateLimit a mt:ApiRateLimit ;
               mt:quotaLimit ?rateLimitPerMinute .

    ?tier rdfs:label ?tierLabel .
}
ORDER BY DESC(?rateLimitPerMinute)

# ============================================================================
# Query 11: Identify Tenants Requiring Backup
# ============================================================================
# Returns: Tenants with backup schedules and last backup time

SELECT ?tenantId ?backupSchedule ?lastBackup ?isOverdue
WHERE {
    ?tenant mt:tenantId ?tenantId ;
            mt:hasBackupSchedule ?schedule ;
            mt:lastBackupAt ?lastBackup .

    ?schedule rdfs:label ?backupSchedule .

    BIND(NOW() AS ?now)
    BIND(
        IF(?schedule = mt:HourlyBackup, (?now - ?lastBackup) > (60 * 60),
        IF(?schedule = mt:DailyBackup, (?now - ?lastBackup) > (24 * 60 * 60),
        false))
        AS ?isOverdue
    )

    FILTER(?isOverdue = true)
}

# ============================================================================
# Query 12: Generate Tenant Isolation Rules for Row-Level Security
# ============================================================================
# Returns: SQL RLS policies for row-level isolation

SELECT ?tenantId ?policyName ?policyDefinition
WHERE {
    ?tenant mt:tenantId ?tenantId ;
            mt:hasIsolationStrategy mt:RowLevelIsolation .

    BIND(CONCAT("rls_policy_", ?tenantId) AS ?policyName)
    BIND(CONCAT("tenant_id = '", ?tenantId, "'") AS ?policyDefinition)
}

# ============================================================================
# End of Multi-Tenant SaaS SPARQL Queries
# ============================================================================
