import { GraphQLError } from 'graphql'
import { Context } from '../types/context'
import * as resourceService from '../services/resource'
import * as siteService from '../services/site'
import * as userService from '../services/user'
import * as authService from '../services/auth'
import * as resourceInventoryService from '../services/resource-inventory'
import * as resourceGraphService from '../services/resource-graph'
import * as policyService from '../services/policy-engine'
import * as regionService from '../services/region'
import * as metricsService from '../services/metrics'
import * as wafService from '../services/waf'
import * as anomalyDetectionService from '../services/anomaly-detection'
import * as predictiveAnalyticsService from '../services/predictive-analytics'
import { tenantService } from '../services/tenant'
import { billingService } from '../services/billing'
import { omadaService } from '../services/omada'
import { catalogService } from '../services/catalog'
import { templateService } from '../services/template'
import { deploymentService } from '../services/deployment'
import { blockchainLifecycleManager } from '../services/blockchain-lifecycle'
import { popMappingService } from '../services/pop-mapping'
import { federationCoordinator } from '../services/federation-coordinator'
import { wellArchitectedIndustryService } from '../services/well-architected-industry'
import { sovereigntyZoneService } from '../services/sovereignty-zone'
import * as apiKeyService from '../services/api-key'
import * as testEnvironmentService from '../services/test-environment'
import * as mfaService from '../services/mfa'
import * as forumService from '../services/forum'
import * as apiMarketplaceService from '../services/api-marketplace'
import * as analyticsService from '../services/analytics'
import * as aiOptimizationService from '../services/ai-optimization'
import { infrastructureResolvers } from '../resolvers/infrastructure'
import {
  createTenantInputSchema,
  updateTenantInputSchema,
  budgetInputSchema,
  billingAlertInputSchema,
  resourceRequestInputSchema,
  validateInput,
} from '../lib/validation.js'
import { ZodError } from 'zod'

interface TimeRange {
  start: Date | string
  end: Date | string
}

export const resolvers = {
  Query: {
    health: () => ({
      status: 'ok',
      timestamp: new Date(),
      version: process.env.npm_package_version || '1.0.0',
    }),

    resources: async (_: unknown, args: { filter?: resourceService.ResourceFilter }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceService.getResources(context, args.filter)
    },

    resource: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceService.getResource(context, args.id)
    },

    sites: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return siteService.getSites(context)
    },

    site: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return siteService.getSite(context, args.id)
    },

    me: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return context.user
    },

    users: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return userService.getUsers(context)
    },

    user: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return userService.getUser(context, args.id)
    },

    // API Keys
    apiKeys: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return apiKeyService.getApiKeys(context)
    },

    apiKey: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return apiKeyService.getApiKey(context, args.id)
    },

    // Test Environments
    testEnvironments: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return testEnvironmentService.getTestEnvironments(context)
    },

    testEnvironment: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return testEnvironmentService.getTestEnvironment(context, args.id)
    },

    // Tenants (Sovereign, Superior to Azure)
    tenants: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return tenantService.listTenants()
    },

    tenant: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      // Users can only access their own tenant unless admin
      const tenant = await tenantService.getTenant(args.id)
      if (context.user.role !== 'ADMIN' && !context.tenantContext?.tenantId) {
        throw new GraphQLError('Access denied', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return tenant
    },

    tenantByDomain: async (_: unknown, args: { domain: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return tenantService.getTenantByDomain(args.domain)
    },

    myTenant: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user || !context.tenantContext?.tenantId) {
        throw new GraphQLError('No tenant context', {
          extensions: { code: 'TENANT_REQUIRED' },
        })
      }
      return tenantService.getTenant(context.tenantContext.tenantId)
    },

    tenantUsage: async (
      _: unknown,
      args: { tenantId: string; timeRange: TimeRange },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      // Verify tenant access
      if (context.user.role !== 'ADMIN' && context.tenantContext?.tenantId !== args.tenantId) {
        throw new GraphQLError('Access denied', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return billingService.getUsageReport(
        args.tenantId,
        {
          start: new Date(args.timeRange.start),
          end: new Date(args.timeRange.end),
        },
        'HOUR'
      )
    },

    // Billing (Superior to Azure Cost Management)
    usage: async (
      _: unknown,
      args: { tenantId: string; timeRange: TimeRange; granularity: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      if (context.user.role !== 'ADMIN' && context.tenantContext?.tenantId !== args.tenantId) {
        throw new GraphQLError('Access denied', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return billingService.getUsageReport(
        args.tenantId,
        {
          start: new Date(args.timeRange.start),
          end: new Date(args.timeRange.end),
        },
        args.granularity as 'SECOND' | 'MINUTE' | 'HOUR' | 'DAY'
      )
    },

    usageByResource: async (
      _: unknown,
      args: { tenantId: string; resourceId: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      // Implementation would get usage for specific resource
      throw new GraphQLError('Not yet implemented', {
        extensions: { code: 'NOT_IMPLEMENTED' },
      })
    },

    costBreakdown: async (
      _: unknown,
      args: { tenantId: string; groupBy: string[] },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      if (context.user.role !== 'ADMIN' && context.tenantContext?.tenantId !== args.tenantId) {
        throw new GraphQLError('Access denied', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      const endDate = new Date()
      const startDate = new Date()
      startDate.setDate(startDate.getDate() - 30)
      return billingService.getCostBreakdown(args.tenantId, args.groupBy, {
        start: startDate,
        end: endDate,
      })
    },

    invoice: async (
      _: unknown,
      args: { tenantId: string; invoiceId: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      // Verify tenant access
      if (context.tenantContext?.tenantId && context.tenantContext.tenantId !== args.tenantId) {
        if (!context.tenantContext.isSystemAdmin) {
          throw new GraphQLError('Access denied', {
            extensions: { code: 'FORBIDDEN' },
          })
        }
      }

      try {
        return await billingService.getInvoice(args.invoiceId)
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Failed to get invoice'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },

    invoices: async (
      _: unknown,
      args: {
        tenantId: string
        status?: string
        startDate?: string
        endDate?: string
        limit?: number
        offset?: number
      },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      // Verify tenant access
      if (context.tenantContext?.tenantId && context.tenantContext.tenantId !== args.tenantId) {
        if (!context.tenantContext.isSystemAdmin) {
          throw new GraphQLError('Access denied', {
            extensions: { code: 'FORBIDDEN' },
          })
        }
      }

      try {
        const result = await billingService.getInvoices(args.tenantId, {
          status: args.status,
          startDate: args.startDate ? new Date(args.startDate) : undefined,
          endDate: args.endDate ? new Date(args.endDate) : undefined,
          limit: args.limit,
          offset: args.offset,
        })
        return result.invoices
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Failed to list invoices'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },

    costForecast: async (
      _: unknown,
      args: { tenantId: string; timeframe: string; confidence: number },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      if (context.user.role !== 'ADMIN' && context.tenantContext?.tenantId !== args.tenantId) {
        throw new GraphQLError('Access denied', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return billingService.getCostForecast(args.tenantId, args.timeframe, args.confidence)
    },

    costOptimization: async (_: unknown, args: { tenantId: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      if (context.user.role !== 'ADMIN' && context.tenantContext?.tenantId !== args.tenantId) {
        throw new GraphQLError('Access denied', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      const recommendations = await aiOptimizationService.getCostOptimizationRecommendations(context, args.tenantId)
      return recommendations.map(rec => ({
        id: rec.id,
        type: rec.type,
        title: rec.title,
        description: rec.description,
        potentialSavings: rec.potentialSavings,
        impact: rec.impact,
        effort: rec.effort,
      }))
    },

    billingAlerts: async (_: unknown, args: { tenantId: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      // Verify tenant access
      if (context.tenantContext?.tenantId && context.tenantContext.tenantId !== args.tenantId) {
        if (!context.tenantContext.isSystemAdmin) {
          throw new GraphQLError('Access denied', {
            extensions: { code: 'FORBIDDEN' },
          })
        }
      }

      try {
        const { getDb } = await import('../db')
        const db = getDb()
        const result = await db.query(
          `SELECT * FROM billing_alerts WHERE tenant_id = $1 ORDER BY created_at DESC`,
          [args.tenantId]
        )
        return result.rows
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Failed to get billing alerts'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },

    budgets: async (_: unknown, args: { tenantId: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      // Verify tenant access
      if (context.tenantContext?.tenantId && context.tenantContext.tenantId !== args.tenantId) {
        if (!context.tenantContext.isSystemAdmin) {
          throw new GraphQLError('Access denied', {
            extensions: { code: 'FORBIDDEN' },
          })
        }
      }

      try {
        const tracking = await billingService.getBudgetTracking(args.tenantId)
        return tracking
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Failed to get budgets'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },

    resourceInventory: async (
      _: unknown,
      args: { filter?: resourceInventoryService.ResourceInventoryFilter },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceInventoryService.getResourceInventory(context, args.filter)
    },

    resourceInventoryItem: async (
      _: unknown,
      args: { id: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceInventoryService.getResourceInventoryItem(context, args.id)
    },

    resourceGraph: async (
      _: unknown,
      args: { query?: resourceGraphService.GraphQuery },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceGraphService.getResourceGraph(context, args.query)
    },

    resourceDependencies: async (
      _: unknown,
      args: { resourceId: string; maxDepth?: number },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceGraphService.getResourceDependencies(
        context,
        args.resourceId,
        args.maxDepth || 3
      )
    },

    resourceDependents: async (
      _: unknown,
      args: { resourceId: string; maxDepth?: number },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceGraphService.getResourceDependents(
        context,
        args.resourceId,
        args.maxDepth || 3
      )
    },

    resourcePath: async (
      _: unknown,
      args: { sourceResourceId: string; targetResourceId: string; maxDepth?: number },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceGraphService.findResourcePath(
        context,
        args.sourceResourceId,
        args.targetResourceId,
        args.maxDepth || 10
      )
    },

    resourcesByProvider: async (
      _: unknown,
      args: { provider: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceGraphService.getResourcesByProvider(context, args.provider)
    },

    resourcesByRegion: async (
      _: unknown,
      args: { region: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceGraphService.getResourcesByRegion(context, args.region)
    },

    resourcesByTags: async (
      _: unknown,
      args: { tags: string[] },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceGraphService.getResourcesByTags(context, args.tags)
    },

    policies: async (
      _: unknown,
      args: { filter?: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return policyService.getPolicies(context, args.filter)
    },

    policy: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return policyService.getPolicy(context, args.id)
    },

    policyViolations: async (
      _: unknown,
      args: { filter?: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return policyService.getPolicyViolations(context, args.filter)
    },

    regions: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return regionService.getRegions(context)
    },

    region: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return regionService.getRegion(context, args.id)
    },

    regionByCode: async (_: unknown, args: { code: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return regionService.getRegionByCode(context, args.code)
    },

    metrics: async (
      _: unknown,
      args: { resourceId: string; metricType: string; timeRange: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return metricsService.getMetrics(context, {
        resourceId: args.resourceId,
        metricType: args.metricType,
        timeRange: {
          start: new Date(args.timeRange.start),
          end: new Date(args.timeRange.end),
        },
      })
    },

    pillars: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return wafService.getPillars(context)
    },

    pillar: async (_: unknown, args: { code: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return wafService.getPillarByCode(context, args.code)
    },

    findings: async (
      _: unknown,
      args: { filter?: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return wafService.getFindings(context, args.filter)
    },

    risks: async (
      _: unknown,
      args: { resourceId?: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return wafService.getRisks(context, args.resourceId)
    },

    culturalContext: async (
      _: unknown,
      args: { regionId: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      const { getCulturalContext } = await import('../services/cultural-context')
      return getCulturalContext(context, args.regionId)
    },

    anomalies: async (
      _: unknown,
      args: { resourceId?: string; limit?: number },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return anomalyDetectionService.getAnomalies(context, args.resourceId, args.limit || 100)
    },

    predictions: async (
      _: unknown,
      args: { resourceId?: string; limit?: number },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return predictiveAnalyticsService.getPredictions(context, args.resourceId, args.limit || 50)
    },
  },

  Mutation: {
    login: async (_: unknown, args: { email: string; password: string }) => {
      return authService.login(args.email, args.password)
    },

    logout: async (_: unknown, __: unknown, _context: Context) => {
      // In a real implementation, invalidate the token
      return true
    },

    // Two-Factor Authentication
    setup2FA: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      const result = await mfaService.generateTOTPSecret(context.user.id, context.user.email)
      return {
        secret: result.secret,
        qrCodeUrl: result.qrCodeUrl,
      }
    },

    verify2FA: async (_: unknown, args: { code: string; secret: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      // For verification during setup, we need to verify against the provided secret
      // This is a simplified version - in production, use the stored secret
      const isValid = await mfaService.verifyTOTP(context.user.id, args.code)
      return {
        valid: isValid,
        enabled: false,
      }
    },

    enable2FA: async (_: unknown, args: { code: string; secret: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      const isValid = await mfaService.verifyTOTP(context.user.id, args.code)
      if (!isValid) {
        throw new GraphQLError('Invalid verification code', {
          extensions: { code: 'VALIDATION_ERROR' },
        })
      }
      await mfaService.enableMFA(context.user.id, 'totp')
      return true
    },

    disable2FA: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      await mfaService.disableMFA(context.user.id, 'totp')
      return true
    },

    // API Keys
    createApiKey: async (
      _: unknown,
      args: { input: apiKeyService.CreateApiKeyInput },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return apiKeyService.createApiKey(context, args.input)
    },

    updateApiKey: async (
      _: unknown,
      args: { id: string; input: apiKeyService.UpdateApiKeyInput },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return apiKeyService.updateApiKey(context, args.id, args.input)
    },

    revokeApiKey: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return apiKeyService.revokeApiKey(context, args.id)
    },

    // Test Environments
    createTestEnvironment: async (
      _: unknown,
      args: { input: testEnvironmentService.CreateTestEnvironmentInput },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return testEnvironmentService.createTestEnvironment(context, args.input)
    },

    updateTestEnvironment: async (
      _: unknown,
      args: { id: string; input: testEnvironmentService.UpdateTestEnvironmentInput },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      // Implementation would update the environment
      return testEnvironmentService.getTestEnvironment(context, args.id)
    },

    startTestEnvironment: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return testEnvironmentService.startTestEnvironment(context, args.id)
    },

    stopTestEnvironment: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return testEnvironmentService.stopTestEnvironment(context, args.id)
    },

    deleteTestEnvironment: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return testEnvironmentService.deleteTestEnvironment(context, args.id)
    },

    createResource: async (
      _: unknown,
      args: { input: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceService.createResource(context, args.input)
    },

    updateResource: async (
      _: unknown,
      args: { id: string; input: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceService.updateResource(context, args.id, args.input)
    },

    deleteResource: async (
      _: unknown,
      args: { id: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceService.deleteResource(context, args.id)
    },

    createUser: async (
      _: unknown,
      args: { input: any },
      context: Context
    ) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return userService.createUser(context, args.input)
    },

    updateUser: async (
      _: unknown,
      args: { id: string; input: any },
      context: Context
    ) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return userService.updateUser(context, args.id, args.input)
    },

    deleteUser: async (
      _: unknown,
      args: { id: string },
      context: Context
    ) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return userService.deleteUser(context, args.id)
    },

    createResourceInventoryItem: async (
      _: unknown,
      args: { input: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceInventoryService.createResourceInventoryItem(context, args.input)
    },

    updateResourceInventoryItem: async (
      _: unknown,
      args: { id: string; input: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceInventoryService.updateResourceInventoryItem(
        context,
        args.id,
        args.input
      )
    },

    deleteResourceInventoryItem: async (
      _: unknown,
      args: { id: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceInventoryService.deleteResourceInventoryItem(context, args.id)
    },

    syncResourceInventory: async (
      _: unknown,
      args: { provider: string; resources: any[] },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      const synced = await resourceInventoryService.syncResourceInventory(
        context,
        args.provider,
        args.resources
      )
      return { synced, provider: args.provider }
    },

    createResourceRelationship: async (
      _: unknown,
      args: {
        sourceResourceId: string
        targetResourceId: string
        relationshipType: string
        metadata?: any
      },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceGraphService.createResourceRelationship(
        context,
        args.sourceResourceId,
        args.targetResourceId,
        args.relationshipType,
        args.metadata
      )
    },

    deleteResourceRelationship: async (
      _: unknown,
      args: { id: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return resourceGraphService.deleteResourceRelationship(context, args.id)
    },

    createPolicy: async (
      _: unknown,
      args: { input: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return policyService.createPolicy(context, args.input)
    },

    updatePolicy: async (
      _: unknown,
      args: { id: string; input: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return policyService.updatePolicy(context, args.id, args.input)
    },

    deletePolicy: async (
      _: unknown,
      args: { id: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return policyService.deletePolicy(context, args.id)
    },

    evaluatePolicy: async (
      _: unknown,
      args: { policyId: string; resourceId: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return policyService.evaluatePolicy(context, args.policyId, args.resourceId)
    },

    evaluateAllPolicies: async (
      _: unknown,
      args: { resourceId?: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      const evaluated = await policyService.evaluateAllPolicies(
        context,
        args.resourceId
      )
      return { evaluated }
    },

    resolveViolation: async (
      _: unknown,
      args: { violationId: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return policyService.resolveViolation(context, args.violationId)
    },

    detectAnomalies: async (
      _: unknown,
      args: { config: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return anomalyDetectionService.detectAnomalies(context, args.config)
    },

    detectAnomaliesForAllResources: async (
      _: unknown,
      args: { metricTypes?: string[] },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return anomalyDetectionService.detectAnomaliesForAllResources(context, args.metricTypes)
    },

    predictUsage: async (
      _: unknown,
      args: { config: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return predictiveAnalyticsService.predictUsage(context, args.config)
    },

    predictCost: async (
      _: unknown,
      args: { resourceId: string; timeframe: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return predictiveAnalyticsService.predictCost(context, args.resourceId, args.timeframe as any)
    },

    predictCapacity: async (
      _: unknown,
      args: { resourceId: string; metricType: string; timeframe: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return predictiveAnalyticsService.predictCapacity(
        context,
        args.resourceId,
        args.metricType as any,
        args.timeframe as any
      )
    },

    predictFailure: async (
      _: unknown,
      args: { resourceId: string; timeframe?: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return predictiveAnalyticsService.predictFailure(
        context,
        args.resourceId,
        (args.timeframe as any) || '24H'
      )
    },

    // Marketplace Catalog Queries
    publishers: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return catalogService.getPublishers(context)
    },

    publisher: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return catalogService.getPublisher(context, args.id)
    },

    products: async (
      _: unknown,
      args: { filter?: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return catalogService.getProducts(context, args.filter)
    },

    product: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return catalogService.getProduct(context, args.id)
    },

    productBySlug: async (
      _: unknown,
      args: { slug: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return catalogService.getProductBySlug(context, args.slug)
    },

    productReviews: async (
      _: unknown,
      args: { productId: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return catalogService.getProductReviews(context, args.productId)
    },

    // Templates
    templates: async (_: unknown, args: { filter?: any }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return templateService.getTemplates(context, args.filter)
    },

    template: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return templateService.getTemplate(context, args.id)
    },

    templateBySlug: async (
      _: unknown,
      args: { slug: string; version?: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return templateService.getTemplateBySlug(context, args.slug, args.version)
    },

    // Deployments
    deployments: async (_: unknown, args: { filter?: any }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return deploymentService.getDeployments(context, args.filter)
    },

    deployment: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return deploymentService.getDeployment(context, args.id)
    },

    deploymentLogs: async (
      _: unknown,
      args: { deploymentId: string; limit?: number },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return deploymentService.getDeploymentLogs(context, args.deploymentId, args.limit)
    },

    // Blockchain Networks
    blockchainNetworks: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      // Get all networks - would need a list method
      return []
    },

    blockchainNetwork: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return blockchainLifecycleManager.getNetwork(context, args.id)
    },

    blockchainNodes: async (_: unknown, args: { networkId: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return blockchainLifecycleManager.getNodes(context, args.networkId)
    },

    // PoP Mappings
    popMappings: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return popMappingService.getPoPMappings(context)
    },

    popMapping: async (_: unknown, args: { popId: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return popMappingService.getPoPMapping(context, args.popId)
    },

    // Sovereignty Zones
    sovereigntyZones: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return sovereigntyZoneService.getZones(context)
    },

    sovereigntyZone: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return sovereigntyZoneService.getZone(context, args.id)
    },

    // Well-Architected Framework
    industryControls: async (_: unknown, args: { industry: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return wellArchitectedIndustryService.getIndustryControls(context, args.industry as any)
    },

    wafAssessment: async (_: unknown, args: { resourceId: string; industry: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return wellArchitectedIndustryService.assessResource(context, args.resourceId, args.industry as any)
    },

    // Community Forum
    forumCategories: async (_: unknown, __: unknown, context: Context) => {
      return forumService.getForumCategories()
    },

    forumCategory: async (_: unknown, args: { id: string }, context: Context) => {
      return forumService.getForumCategory(args.id)
    },

    forumPosts: async (_: unknown, args: { filter: any }, context: Context) => {
      return forumService.getForumPosts(args.filter || {})
    },

    forumPost: async (_: unknown, args: { id: string }, context: Context) => {
      return forumService.getForumPost(args.id)
    },

    forumReplies: async (_: unknown, args: { postId: string }, context: Context) => {
      return forumService.getForumReplies(args.postId)
    },

    // API Marketplace
    apiMarketplaceListings: async (_: unknown, args: { filter: any }, context: Context) => {
      return apiMarketplaceService.getAPIMarketplaceListings(args.filter)
    },

    apiMarketplaceListing: async (_: unknown, args: { id: string }, context: Context) => {
      return apiMarketplaceService.getAPIMarketplaceListing(args.id)
    },

    myAPISubscriptions: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return apiMarketplaceService.getMyAPISubscriptions(context)
    },

    // Analytics
    analyticsRevenue: async (_: unknown, args: { timeRange: TimeRange }, context: Context) => {
      return analyticsService.getAnalyticsRevenue(context, {
        start: new Date(args.timeRange.start),
        end: new Date(args.timeRange.end),
      })
    },

    analyticsUsers: async (_: unknown, args: { timeRange: TimeRange }, context: Context) => {
      return analyticsService.getAnalyticsUsers(context, {
        start: new Date(args.timeRange.start),
        end: new Date(args.timeRange.end),
      })
    },

    analyticsAPIUsage: async (_: unknown, args: { timeRange: TimeRange }, context: Context) => {
      return analyticsService.getAnalyticsAPIUsage(context, {
        start: new Date(args.timeRange.start),
        end: new Date(args.timeRange.end),
      })
    },

    analyticsGrowth: async (_: unknown, __: unknown, context: Context) => {
      return analyticsService.getAnalyticsGrowth(context)
    },

    // AI Optimization
    optimizationRecommendations: async (_: unknown, args: { tenantId?: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return aiOptimizationService.getOptimizationRecommendations(context, args.tenantId)
    },

    // Infrastructure Documentation
    ...infrastructureResolvers.Query,

    // Omada Infrastructure
    omadaSites: async (_: unknown, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return omadaService.getSites(context)
    },

    omadaSite: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return omadaService.getSite(context, args.id)
    },

    omadaAccessPoints: async (
      _: unknown,
      args: { siteId: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return omadaService.getAccessPoints(context, args.siteId)
    },

    omadaAccessPoint: async (
      _: unknown,
      args: { id: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return omadaService.getAccessPoint(context, args.id)
    },

    omadaClients: async (
      _: unknown,
      args: { siteId: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return omadaService.getClients(context, args.siteId)
    },

    omadaClient: async (
      _: unknown,
      args: { mac: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return omadaService.getClient(context, args.mac)
    },

    omadaSsids: async (
      _: unknown,
      args: { siteId: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return omadaService.getSsids(context, args.siteId)
    },

    // Billing Mutations
    createInvoice: async (
      _: unknown,
      args: {
        tenantId: string
        billingPeriodStart: string
        billingPeriodEnd: string
        status?: string
        currency?: string
      },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      // Verify tenant access
      if (context.tenantContext?.tenantId && context.tenantContext.tenantId !== args.tenantId) {
        if (!context.tenantContext.isSystemAdmin) {
          throw new GraphQLError('Access denied', {
            extensions: { code: 'FORBIDDEN' },
          })
        }
      }

      try {
        const invoiceId = await billingService.createInvoice(
          args.tenantId,
          new Date(args.billingPeriodStart),
          new Date(args.billingPeriodEnd),
          {
            status: (args.status as any) || 'PENDING',
            currency: args.currency,
          }
        )
        return await billingService.getInvoice(invoiceId)
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Failed to create invoice'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },

    setBudget: async (
      _: unknown,
      args: {
        tenantId: string
        budget: {
          name: string
          amount: number
          period: string
          startDate: string
          endDate?: string
        }
      },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      // Verify tenant access
      if (context.tenantContext?.tenantId && context.tenantContext.tenantId !== args.tenantId) {
        if (!context.tenantContext.isSystemAdmin) {
          throw new GraphQLError('Access denied', {
            extensions: { code: 'FORBIDDEN' },
          })
        }
      }

      try {
        const validatedBudget = validateInput(budgetInputSchema, {
          ...args.budget,
          startDate: args.budget.startDate,
          endDate: args.budget.endDate || null,
        })
        const budgetId = await billingService.createBudget(
          args.tenantId,
          validatedBudget.name,
          validatedBudget.amount,
          validatedBudget.period,
          new Date(validatedBudget.startDate),
          validatedBudget.endDate ? new Date(validatedBudget.endDate) : undefined
        )
        const tracking = await billingService.getBudgetTracking(args.tenantId, budgetId)
        return tracking[0]
      } catch (error: unknown) {
        if (error instanceof ZodError) {
          throw new GraphQLError('Invalid budget input', {
            extensions: { code: 'BAD_USER_INPUT', details: error.errors.map(e => e.message).join(', ') },
          })
        }
        const message = error instanceof Error ? error.message : 'Failed to create budget'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },

    updateBudget: async (
      _: unknown,
      args: {
        id: string
        input: {
          name?: string
          amount?: number
          endDate?: string
        }
      },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      try {
        await billingService.updateBudget(args.id, {
          name: args.input.name,
          amount: args.input.amount,
          endDate: args.input.endDate ? new Date(args.input.endDate) : undefined,
        })
        const { getDb } = await import('../db')
        const db = getDb()
        const result = await db.query(`SELECT * FROM budgets WHERE id = $1`, [args.id])
        if (result.rows.length === 0) {
          throw new Error('Budget not found')
        }
        const tenantId = result.rows[0].tenant_id
        const tracking = await billingService.getBudgetTracking(tenantId, args.id)
        return tracking[0]
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Failed to update budget'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },

    deleteBudget: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      try {
        await billingService.deleteBudget(args.id)
        return true
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Failed to delete budget'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },

    createBillingAlert: async (
      _: unknown,
      args: {
        tenantId: string
        alert: {
          name: string
          alertType: string
          conditionType: string
          thresholdValue: number
          enabled?: boolean
        }
      },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      // Verify tenant access
      if (context.tenantContext?.tenantId && context.tenantContext.tenantId !== args.tenantId) {
        if (!context.tenantContext.isSystemAdmin) {
          throw new GraphQLError('Access denied', {
            extensions: { code: 'FORBIDDEN' },
          })
        }
      }

      try {
        const validatedAlert = validateInput(billingAlertInputSchema, {
          name: args.alert.name,
          alertType: args.alert.alertType,
          threshold: args.alert.thresholdValue,
          condition: { conditionType: args.alert.conditionType },
          enabled: args.alert.enabled !== undefined ? args.alert.enabled : true,
        })
        const alertId = await billingService.createBillingAlert(
          args.tenantId,
          validatedAlert.name,
          validatedAlert.alertType,
          args.alert.conditionType,
          validatedAlert.threshold || 0,
          validatedAlert.enabled !== undefined ? validatedAlert.enabled : true
        )
        const { getDb } = await import('../db')
        const db = getDb()
        const result = await db.query(`SELECT * FROM billing_alerts WHERE id = $1`, [alertId])
        return result.rows[0]
      } catch (error: unknown) {
        if (error instanceof ZodError) {
          throw new GraphQLError('Invalid billing alert input', {
            extensions: { code: 'BAD_USER_INPUT', details: error.errors.map(e => e.message).join(', ') },
          })
        }
        const message = error instanceof Error ? error.message : 'Failed to create billing alert'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },

    updateBillingAlert: async (
      _: unknown,
      args: {
        id: string
        input: {
          name?: string
          enabled?: boolean
          thresholdValue?: number
        }
      },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      try {
        await billingService.updateBillingAlert(args.id, {
          name: args.input.name,
          enabled: args.input.enabled,
          thresholdValue: args.input.thresholdValue,
        })
        const { getDb } = await import('../db')
        const db = getDb()
        const result = await db.query(`SELECT * FROM billing_alerts WHERE id = $1`, [args.id])
        if (result.rows.length === 0) {
          throw new Error('Billing alert not found')
        }
        return result.rows[0]
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Failed to update billing alert'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },

    deleteBillingAlert: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      try {
        await billingService.deleteBillingAlert(args.id)
        return true
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Failed to delete billing alert'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },

    // Marketplace Catalog Mutations
    createPublisher: async (_: unknown, args: { input: any }, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return catalogService.createPublisher(context, args.input)
    },

    createProduct: async (_: unknown, args: { input: any }, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return catalogService.createProduct(context, args.input)
    },

    updateProduct: async (
      _: unknown,
      args: { id: string; input: any },
      context: Context
    ) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return catalogService.updateProduct(context, args.id, args.input)
    },

    createProductVersion: async (_: unknown, args: { input: any }, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return catalogService.createProductVersion(context, args.input)
    },

    createPricingModel: async (_: unknown, args: { input: any }, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return catalogService.createPricingModel(context, args.input)
    },

    createProductReview: async (_: unknown, args: { input: any }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return catalogService.createProductReview(context, args.input)
    },

    // Template Mutations
    createTemplate: async (_: unknown, args: { input: any }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return templateService.createTemplate(context, args.input)
    },

    updateTemplate: async (
      _: unknown,
      args: { id: string; input: any },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return templateService.updateTemplate(context, args.id, args.input)
    },

    createTemplateVersion: async (_: unknown, args: { input: any }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return templateService.createTemplateVersion(context, args.input)
    },

    // Deployment Mutations
    createDeployment: async (_: unknown, args: { input: any }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return deploymentService.createDeployment(context, args.input)
    },

    deleteDeployment: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return deploymentService.deleteDeployment(context, args.id)
    },

    // Blockchain Network Mutations
    createBlockchainNetwork: async (_: unknown, args: { input: any }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return blockchainLifecycleManager.createNetwork(context, args.input)
    },

    createBlockchainNode: async (_: unknown, args: { networkId: string; input: any }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return blockchainLifecycleManager.createNode(context, args.networkId, args.input)
    },

    // PoP Mapping Mutations
    mapPoPToRegion: async (_: unknown, args: { popLocation: any }, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return popMappingService.mapPoPToRegion(context, args.popLocation)
    },

    // Sovereignty Zone Mutations
    createSovereigntyZone: async (_: unknown, args: { input: any }, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return sovereigntyZoneService.createZone(context, args.input)
    },

    createDataResidencyRule: async (_: unknown, args: { input: any }, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return sovereigntyZoneService.createDataResidencyRule(context, args.input)
    },

    // WAF Mutations
    assessResourceWAF: async (_: unknown, args: { resourceId: string; industry: string }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return wellArchitectedIndustryService.assessResource(context, args.resourceId, args.industry as any)
    },

    // Community Forum Mutations
    createForumPost: async (_: unknown, args: { input: any }, context: Context) => {
      return forumService.createForumPost(context, args.input)
    },

    updateForumPost: async (_: unknown, args: { id: string; input: any }, context: Context) => {
      return forumService.updateForumPost(context, args.id, args.input)
    },

    deleteForumPost: async (_: unknown, args: { id: string }, context: Context) => {
      return forumService.deleteForumPost(context, args.id)
    },

    createForumReply: async (_: unknown, args: { input: any }, context: Context) => {
      return forumService.createForumReply(context, args.input)
    },

    updateForumReply: async (_: unknown, args: { id: string; input: any }, context: Context) => {
      return forumService.updateForumReply(context, args.id, args.input)
    },

    deleteForumReply: async (_: unknown, args: { id: string }, context: Context) => {
      return forumService.deleteForumReply(context, args.id)
    },

    // API Marketplace Mutations
    createAPIMarketplaceListing: async (_: unknown, args: { input: any }, context: Context) => {
      return apiMarketplaceService.createAPIMarketplaceListing(context, args.input)
    },

    updateAPIMarketplaceListing: async (_: unknown, args: { id: string; input: any }, context: Context) => {
      return apiMarketplaceService.updateAPIMarketplaceListing(context, args.id, args.input)
    },

    deleteAPIMarketplaceListing: async (_: unknown, args: { id: string }, context: Context) => {
      return apiMarketplaceService.deleteAPIMarketplaceListing(context, args.id)
    },

    subscribeToAPI: async (_: unknown, args: { listingId: string }, context: Context) => {
      return apiMarketplaceService.subscribeToAPI(context, args.listingId)
    },

    unsubscribeFromAPI: async (_: unknown, args: { subscriptionId: string }, context: Context) => {
      return apiMarketplaceService.unsubscribeFromAPI(context, args.subscriptionId)
    },

    // Infrastructure Documentation Mutations
    ...infrastructureResolvers.Mutation,

    // Tenant Mutations
    createTenant: async (_: unknown, args: { input: { name: string; domain?: string; tier?: string; metadata?: Record<string, unknown>; quotaLimits?: Record<string, unknown> } }, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      try {
        const validatedInput = validateInput(createTenantInputSchema, args.input)
        return tenantService.createTenant(validatedInput)
      } catch (error: unknown) {
        if (error instanceof ZodError) {
          throw new GraphQLError('Invalid input', {
            extensions: { code: 'BAD_USER_INPUT', details: error.errors.map(e => e.message).join(', ') },
          })
        }
        throw error
      }
    },

    updateTenant: async (_: unknown, args: { id: string; input: { name?: string; domain?: string; status?: string; tier?: string; metadata?: Record<string, unknown>; quotaLimits?: Record<string, unknown> } }, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      if (context.user.role !== 'ADMIN' && context.tenantContext?.tenantId !== args.id) {
        throw new GraphQLError('Access denied', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      try {
        const validatedInput = validateInput(updateTenantInputSchema, args.input)
        return tenantService.updateTenant(args.id, validatedInput)
      } catch (error: unknown) {
        if (error instanceof ZodError) {
          throw new GraphQLError('Invalid input', {
            extensions: { code: 'BAD_USER_INPUT', details: error.errors.map(e => e.message).join(', ') },
          })
        }
        throw error
      }
    },

    deleteTenant: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      await tenantService.deleteTenant(args.id)
      return true
    },

    suspendTenant: async (_: unknown, args: { id: string; reason: string }, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      await tenantService.suspendTenant(args.id, args.reason)
      return true
    },

    activateTenant: async (_: unknown, args: { id: string }, context: Context) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      await tenantService.activateTenant(args.id)
      return true
    },

    addUserToTenant: async (
      _: unknown,
      args: { tenantId: string; userId: string; role: string; permissions?: Record<string, unknown> },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      if (context.user.role !== 'ADMIN' && context.tenantContext?.tenantId !== args.tenantId) {
        throw new GraphQLError('Access denied', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      await tenantService.addUserToTenant(args.tenantId, args.userId, args.role, args.permissions)
      return true
    },

    removeUserFromTenant: async (
      _: unknown,
      args: { tenantId: string; userId: string },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      if (context.user.role !== 'ADMIN' && context.tenantContext?.tenantId !== args.tenantId) {
        throw new GraphQLError('Access denied', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      await tenantService.removeUserFromTenant(args.tenantId, args.userId)
      return true
    },

    updateTenantQuotas: async (
      _: unknown,
      args: { tenantId: string; quotas: any },
      context: Context
    ) => {
      if (!context.user || context.user.role !== 'ADMIN') {
        throw new GraphQLError('Admin access required', {
          extensions: { code: 'FORBIDDEN' },
        })
      }
      return tenantService.updateTenant(args.tenantId, { quotaLimits: args.quotas })
    },

    shareResourceAcrossTenants: async (
      _: unknown,
      args: { resourceId: string; targetTenants: string[] },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      if (!context.tenantContext?.tenantId) {
        throw new GraphQLError('Tenant context required', {
          extensions: { code: 'TENANT_REQUIRED' },
        })
      }

      try {
        await tenantService.shareResourceAcrossTenants(
          args.resourceId,
          context.tenantContext.tenantId,
          args.targetTenants
        )
        return true
      } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Failed to share resource'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },

    checkQuota: async (
      _: unknown,
      args: { tenantId: string; resourceRequest: Record<string, unknown> },
      context: Context
    ) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }

      // Verify tenant access
      if (context.user.role !== 'ADMIN' && context.tenantContext?.tenantId !== args.tenantId) {
        throw new GraphQLError('Access denied', {
          extensions: { code: 'FORBIDDEN' },
        })
      }

      try {
        const validatedRequest = validateInput(resourceRequestInputSchema, args.resourceRequest)
        const check = await tenantService.checkQuota(args.tenantId, validatedRequest)
        const tenant = await tenantService.getTenant(args.tenantId)

        return {
          allowed: check.allowed,
          exceeded: check.exceeded,
          current: {
            compute: check.current.compute,
            storage: check.current.storage,
            network: check.current.network,
          },
          limits: tenant.quotaLimits,
        }
      } catch (error: unknown) {
        if (error instanceof ZodError) {
          throw new GraphQLError('Invalid resource request input', {
            extensions: { code: 'BAD_USER_INPUT', details: error.errors.map(e => e.message).join(', ') },
          })
        }
        const message = error instanceof Error ? error.message : 'Failed to check quota'
        throw new GraphQLError(message, {
          extensions: { code: 'INTERNAL_ERROR' },
        })
      }
    },
  },

  Resource: {
    site: async (resource: { siteId: string }, __: unknown, context: Context) => {
      return siteService.getSite(context, resource.siteId)
    },
  },

  Site: {
    resources: async (site: { id: string }, __: unknown, context: Context) => {
      return resourceService.getResources(context, { siteId: site.id })
    },
  },

  ResourceInventoryItem: {
    site: async (item: { siteId: string | null }, __: unknown, context: Context) => {
      if (!item.siteId) {
        return null
      }
      return siteService.getSite(context, item.siteId)
    },
  },

  Tenant: {
    users: async (tenant: { id: string }, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      return tenantService.getTenantUsers(tenant.id)
    },

    resources: async (tenant: { id: string }, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      // Get tenant resources from resource_inventory
      const { getDb } = await import('../db/index.js')
      const db = getDb()
      const result = await db.query(
        `SELECT * FROM resource_inventory WHERE tenant_id = $1 AND status != 'DELETED' ORDER BY created_at DESC`,
        [tenant.id]
      )
      return result.rows.map((row: { id: string; name: string; resource_type: string; status: string; site_id: string | null; metadata: Record<string, unknown> | null; created_at: Date; updated_at: Date }) => ({
        id: row.id,
        name: row.name,
        type: row.resource_type,
        status: row.status,
        site: row.site_id ? { id: row.site_id } : null,
        metadata: row.metadata,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
      }))
    },

    usage: async (tenant: { id: string }, __: unknown, context: Context) => {
      if (!context.user) {
        throw new GraphQLError('Authentication required', {
          extensions: { code: 'UNAUTHENTICATED' },
        })
      }
      // Get current usage metrics from tenant service
      const quotaUsage = await tenantService.getQuotaUsage(tenant.id)
      const { getDb } = await import('../db/index.js')
      const db = getDb()

      // Get current cost from usage records (last 30 days)
      const endDate = new Date()
      const startDate = new Date()
      startDate.setDate(startDate.getDate() - 30)

      const costResult = await db.query(
        `SELECT SUM(cost) as total_cost FROM usage_records
         WHERE tenant_id = $1 AND timestamp >= $2 AND timestamp <= $3`,
        [tenant.id, startDate, endDate]
      )
      const totalCost = parseFloat(costResult.rows[0]?.total_cost || '0')

      // Get cost forecast
      const forecast = await billingService.getCostForecast(tenant.id, '30D', 0.8)

      // Get usage history (last 12 months, monthly snapshots)
      const historyResult = await db.query(
        `SELECT
           date_trunc('month', timestamp) as month,
           SUM(cost) as total
         FROM usage_records
         WHERE tenant_id = $1 AND timestamp >= NOW() - INTERVAL '12 months'
         GROUP BY month
         ORDER BY month DESC`,
        [tenant.id]
      )

      const history = historyResult.rows.map((row: { month: Date; total: string }) => ({
        timestamp: row.month,
        compute: quotaUsage.compute.vcpu * 0.1, // Simplified calculation
        storage: quotaUsage.storage.total * 0.05,
        network: quotaUsage.network.bandwidth * 0.02,
        total: parseFloat(row.total),
      }))

      return {
        current: {
          compute: quotaUsage.compute.vcpu,
          storage: quotaUsage.storage.total,
          network: quotaUsage.network.bandwidth,
          total: totalCost,
          currency: 'USD',
        },
        forecast: {
          predicted: forecast.predictedCost,
          confidence: forecast.confidence,
          timeframe: '30D',
        },
        history,
      }
    },
  },

  OmadaSite: {
    accessPoints: async (parent: { id: string }, __: unknown, context: Context) => {
      return omadaService.getAccessPoints(context, parent.id)
    },
    clients: async (parent: { id: string }, __: unknown, context: Context) => {
      return omadaService.getClients(context, parent.id)
    },
    ssids: async (parent: { id: string }, __: unknown, context: Context) => {
      return omadaService.getSsids(context, parent.id)
    },
  },

  OmadaAccessPoint: {
    site: async (parent: { siteId: string }, __: unknown, context: Context) => {
      return omadaService.getSite(context, parent.siteId)
    },
  },

  OmadaClient: {
    site: async (parent: { siteId: string }, __: unknown, context: Context) => {
      return omadaService.getSite(context, parent.siteId)
    },
    connectedAp: async (parent: { connectedApId: string | null }, __: unknown, context: Context) => {
      if (parent.connectedApId) {
        return omadaService.getAccessPoint(context, parent.connectedApId)
      }
      return null
    },
  },

  OmadaSsid: {
    site: async (parent: { siteId: string }, __: unknown, context: Context) => {
      return omadaService.getSite(context, parent.siteId)
    },
  },

  Product: {
    publisher: async (parent: { publisherId: string }, __: unknown, context: Context) => {
      return catalogService.getPublisher(context, parent.publisherId)
    },
    versions: async (parent: { id: string }, __: unknown, context: Context) => {
      const product = await catalogService.getProduct(context, parent.id)
      return product?.versions || []
    },
    pricing: async (parent: { id: string }, __: unknown, context: Context) => {
      const product = await catalogService.getProduct(context, parent.id)
      return product?.pricing || null
    },
  },

  Deployment: {
    logs: async (parent: { id: string }, __: unknown, context: Context) => {
      return deploymentService.getDeploymentLogs(context, parent.id)
    },
  },

  BlockchainNetwork: {
    nodes: async (parent: { id: string }, __: unknown, context: Context) => {
      return blockchainLifecycleManager.getNodes(context, parent.id)
    },
  },
}

