import { z } from 'zod';
import { baseAppSchema } from './base-app.schema';
import { 
  postgresConfigSchema, 
  mongodbConfigSchema, 
  questdbConfigSchema, 
  dragonflyConfigSchema 
} from './database.schema';

/**
 * Unified application configuration schema that provides both nested and flat access
 * to database configurations for backward compatibility while maintaining a clean structure
 */
export const unifiedAppSchema = baseAppSchema.extend({
  // Flat database configs for DI system (these take precedence)
  redis: dragonflyConfigSchema.optional(),
  mongodb: mongodbConfigSchema.optional(),
  postgres: postgresConfigSchema.optional(),
  questdb: questdbConfigSchema.optional(),
}).transform((data) => {
  // Ensure service.serviceName is set from service.name if not provided
  if (data.service && !data.service.serviceName) {
    data.service.serviceName = data.service.name.replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, '');
  }

  // If flat configs exist, ensure they're also in the nested database object
  if (data.redis || data.mongodb || data.postgres || data.questdb) {
    data.database = {
      ...data.database,
      dragonfly: data.redis || data.database?.dragonfly,
      mongodb: data.mongodb || data.database?.mongodb,
      postgres: data.postgres || data.database?.postgres,
      questdb: data.questdb || data.database?.questdb,
    };
  }

  // If nested configs exist but flat ones don't, copy them to flat structure
  if (data.database) {
    if (data.database.dragonfly && !data.redis) {
      data.redis = data.database.dragonfly;
    }
    if (data.database.mongodb && !data.mongodb) {
      data.mongodb = data.database.mongodb;
    }
    if (data.database.postgres && !data.postgres) {
      data.postgres = data.database.postgres;
    }
    if (data.database.questdb && !data.questdb) {
      // Handle the ilpPort -> influxPort mapping for DI system
      const questdbConfig = { ...data.database.questdb };
      if ('ilpPort' in questdbConfig && !('influxPort' in questdbConfig)) {
        (questdbConfig as any).influxPort = questdbConfig.ilpPort;
      }
      data.questdb = questdbConfig;
    }
  }

  return data;
});

export type UnifiedAppConfig = z.infer<typeof unifiedAppSchema>;

/**
 * Helper to convert StockBotAppConfig to UnifiedAppConfig
 */
export function toUnifiedConfig(config: any): UnifiedAppConfig {
  return unifiedAppSchema.parse(config);
}

/**
 * Helper to get standardized service name
 */
export function getStandardServiceName(serviceName: string): string {
  // Convert camelCase to kebab-case
  return serviceName.replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, '');
}