/**
 * Cultural Context Service
 * Provides cultural intelligence and compliance information for regions
 */

import { Context } from '../types/context'

export async function getCulturalContext(context: Context, regionId: string) {
  const db = context.db

  // Get region
  const regionResult = await db.query('SELECT * FROM regions WHERE id = $1', [regionId])
  if (regionResult.rows.length === 0) {
    throw new Error('Region not found')
  }
  const region = mapRegion(regionResult.rows[0])

  // Get cultural context
  const culturalResult = await db.query(
    'SELECT * FROM cultural_contexts WHERE region_id = $1',
    [regionId]
  )
  const cultural = culturalResult.rows[0] || null

  // Get data residency
  const residencyResult = await db.query(
    'SELECT * FROM data_residency WHERE region_id = $1',
    [regionId]
  )
  const residency = residencyResult.rows[0] || null

  return {
    region,
    language: cultural?.language || null,
    timezone: cultural?.timezone || null,
    culturalNorms: cultural?.cultural_norms || {},
    complianceRequirements: residency?.compliance_frameworks
      ? residency.compliance_frameworks.map((fw: string) => ({
          framework: fw,
          requirements: [], // Would be populated from detailed tables
        }))
      : [],
    dataResidency: residency
      ? {
          region,
          requirements: residency.requirements || [],
          compliance: [],
        }
      : null,
  }
}

function mapRegion(row: any) {
  return {
    id: row.id,
    name: row.name,
    code: row.code,
    country: row.country,
    coordinates: row.latitude && row.longitude
      ? { latitude: parseFloat(row.latitude), longitude: parseFloat(row.longitude) }
      : null,
    metadata: typeof row.metadata === 'string' ? JSON.parse(row.metadata) : (row.metadata || {}),
    createdAt: row.created_at,
    updatedAt: row.updated_at,
  }
}

