import { Migration } from '../migrate.js'

export const up: Migration['up'] = async (db) => {
  // Cultural context table
  await db.query(`
    CREATE TABLE IF NOT EXISTS cultural_contexts (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      region_id UUID NOT NULL REFERENCES regions(id) ON DELETE CASCADE,
      language VARCHAR(100),
      timezone VARCHAR(100),
      cultural_norms JSONB DEFAULT '{}'::jsonb,
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      UNIQUE(region_id)
    )
  `)

  // Data residency requirements
  await db.query(`
    CREATE TABLE IF NOT EXISTS data_residency (
      id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
      region_id UUID NOT NULL REFERENCES regions(id) ON DELETE CASCADE,
      requirements TEXT[] DEFAULT '{}',
      compliance_frameworks TEXT[] DEFAULT '{}',
      created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
      UNIQUE(region_id)
    )
  `)

  // Indexes
  await db.query(`CREATE INDEX IF NOT EXISTS idx_cultural_contexts_region ON cultural_contexts(region_id)`)
  await db.query(`CREATE INDEX IF NOT EXISTS idx_data_residency_region ON data_residency(region_id)`)

  // Triggers
  await db.query(`
    CREATE TRIGGER update_cultural_contexts_updated_at BEFORE UPDATE ON cultural_contexts
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()
  `)
  await db.query(`
    CREATE TRIGGER update_data_residency_updated_at BEFORE UPDATE ON data_residency
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()
  `)
}

export const down: Migration['down'] = async (db) => {
  await db.query(`DROP TRIGGER IF EXISTS update_data_residency_updated_at ON data_residency`)
  await db.query(`DROP TRIGGER IF EXISTS update_cultural_contexts_updated_at ON cultural_contexts`)
  await db.query(`DROP INDEX IF EXISTS idx_data_residency_region`)
  await db.query(`DROP INDEX IF EXISTS idx_cultural_contexts_region`)
  await db.query(`DROP TABLE IF EXISTS data_residency`)
  await db.query(`DROP TABLE IF EXISTS cultural_contexts`)
}

