/**
 * Sovereignty Zone Service
 * Manages sovereign cloud zones and data residency
 */

import { getDb } from '../db/index.js'
import { logger } from '../lib/logger.js'
import { Context } from '../types/context.js'
import { federationCoordinator, SovereigntyZone, DataResidencyRule } from './federation-coordinator.js'

class SovereigntyZoneService {
  /**
   * Create sovereignty zone
   */
  async createZone(
    context: Context,
    input: {
      name: string
      country: string
      region: string
      regulatoryFrameworks?: string[]
      dataResidency: {
        required: boolean
        allowedRegions: string[]
        prohibitedRegions: string[]
      }
    }
  ): Promise<SovereigntyZone> {
    if (!context.user || context.user.role !== 'ADMIN') {
      throw new Error('Admin access required')
    }

    const db = getDb()
    const result = await db.query(
      `INSERT INTO sovereignty_zones (
        name, country, region, regulatory_frameworks, data_residency_rules
      ) VALUES ($1, $2, $3, $4, $5)
      RETURNING *`,
      [
        input.name,
        input.country,
        input.region,
        input.regulatoryFrameworks || [],
        JSON.stringify(input.dataResidency),
      ]
    )

    logger.info('Sovereignty zone created', { zoneId: result.rows[0].id })
    return this.mapZone(result.rows[0])
  }

  /**
   * Get all zones
   */
  async getZones(context: Context): Promise<SovereigntyZone[]> {
    const db = getDb()
    const result = await db.query(`SELECT * FROM sovereignty_zones ORDER BY name`)
    return result.rows.map(this.mapZone)
  }

  /**
   * Get zone by ID
   */
  async getZone(context: Context, id: string): Promise<SovereigntyZone | null> {
    const db = getDb()
    const result = await db.query(
      `SELECT * FROM sovereignty_zones WHERE id = $1`,
      [id]
    )
    if (result.rows.length === 0) return null
    return this.mapZone(result.rows[0])
  }

  /**
   * Create data residency rule
   */
  async createDataResidencyRule(
    context: Context,
    input: {
      dataType: string
      sourceRegion: string
      allowedRegions: string[]
      prohibitedRegions: string[]
      encryptionRequired: boolean
    }
  ): Promise<DataResidencyRule> {
    if (!context.user || context.user.role !== 'ADMIN') {
      throw new Error('Admin access required')
    }

    const db = getDb()
    const result = await db.query(
      `INSERT INTO data_residency_rules (
        data_type, source_region, allowed_regions, prohibited_regions, encryption_required
      ) VALUES ($1, $2, $3, $4, $5)
      RETURNING *`,
      [
        input.dataType,
        input.sourceRegion,
        input.allowedRegions,
        input.prohibitedRegions,
        input.encryptionRequired,
      ]
    )

    logger.info('Data residency rule created', { ruleId: result.rows[0].id })
    return this.mapRule(result.rows[0])
  }

  private mapZone(row: any): SovereigntyZone {
    return {
      id: row.id,
      name: row.name,
      country: row.country,
      region: row.region,
      regulatoryFrameworks: row.regulatory_frameworks || [],
      dataResidency: row.data_residency_rules || {
        required: false,
        allowedRegions: [],
        prohibitedRegions: [],
      },
      datacenterIds: [], // Would be populated from federated_stores
    }
  }

  private mapRule(row: any): DataResidencyRule {
    return {
      id: row.id,
      dataType: row.data_type,
      sourceRegion: row.source_region,
      allowedRegions: row.allowed_regions || [],
      prohibitedRegions: row.prohibited_regions || [],
      encryptionRequired: row.encryption_required,
    }
  }
}

export const sovereigntyZoneService = new SovereigntyZoneService()

