# ============================================
# SOCIAL MEDIA MANAGER - ENHANCED APPLICATION CONFIG
# Version: 2.0 - Advanced Configuration with Java 21 & Spring Boot 3.3
# ============================================

# ============================================
# SERVER CONFIGURATION
# ============================================
server:
  port: ${SERVER_PORT:8000}
  servlet:
    encoding:
      charset: UTF-8
      enabled: true
      force: true
  compression:
    enabled: true
    mime-types: text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json
    min-response-size: 1024
  http2:
    enabled: true
  error:
    include-message: always
    include-binding-errors: always
    include-stacktrace: on-param
    include-exception: false

spring:
  application:
    name: social-media-manager    
  # ============================================
  # DATABASE CONFIGURATION - PostgreSQL 17
  # ============================================
  datasource:
    url: ${DATABASE_URL:jdbc:postgresql://localhost:5432/social_media_manager}
    username: ${DATABASE_USERNAME:postgres}
    password: ${DATABASE_PASSWORD:postgres123}
    driver-class-name: org.postgresql.Driver
    hikari:
      maximum-pool-size: ${DB_POOL_SIZE:25}
      minimum-idle: ${DB_POOL_MIN_IDLE:5}
      idle-timeout: 300000
      connection-timeout: 30000
      max-lifetime: 1800000
      leak-detection-threshold: 60000
      auto-commit: false
      connection-test-query: SELECT 1
      validation-timeout: 5000
      initialization-fail-timeout: 30000
      
  jpa:
    hibernate:
      ddl-auto: ${DDL_AUTO:none}
      naming:
        physical-strategy: org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy
        implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
    show-sql: ${SHOW_SQL:false}
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
        default_schema: core_business
        format_sql: true
        use_sql_comments: true
        jdbc:
          batch_size: 25
          batch_versioned_data: true
          fetch_size: 50
          lob:
            non_contextual_creation: true
        order_inserts: true
        order_updates: true
        generate_statistics: false
        connection:
          provider_disables_autocommit: false
        # Temporarily disable cache until Caffeine dependency is added
        # cache:
        #   use_second_level_cache: true
        #   use_query_cache: true
        #   region:
        #     factory_class: org.hibernate.cache.caffeine.CaffeineCacheRegionFactory
            

  # ============================================
  # NOSQL DATABASES
  # ============================================
  data:
    # REDIS CONFIGURATION
    redis:
      host: ${REDIS_HOST:localhost}
      port: ${REDIS_PORT:6379}
      password: ${REDIS_PASSWORD:}
      database: ${REDIS_DATABASE:0}
      timeout: 3000ms
      lettuce:
        pool:
          max-active: 25
          max-idle: 10
          min-idle: 5
          max-wait: 2000ms
        shutdown-timeout: 2000ms
        
    # MONGODB CONFIGURATION - TEMPORARILY DISABLED
    # mongodb:
    #   uri: ${MONGODB_URI:mongodb://localhost:27017/social_media_logs}
    #   auto-index-creation: true
      
  # ============================================
  # MESSAGING CONFIGURATION - TEMPORARILY SIMPLIFIED
  # ============================================
  
  # RABBITMQ CONFIGURATION - TEMPORARILY DISABLED
  # rabbitmq:
  #   host: ${RABBITMQ_HOST:localhost}
  #   port: ${RABBITMQ_PORT:5672}
  #   username: ${RABBITMQ_USERNAME:guest}
  #   password: ${RABBITMQ_PASSWORD:guest}
  #   virtual-host: ${RABBITMQ_VHOST:/}
  #   connection-timeout: 10s
  #   requested-heartbeat: 30s
  #   listener:
  #     simple:
  #       retry:
  #         enabled: true
  #         initial-interval: 1000ms
  #         max-attempts: 5
  #         multiplier: 2
  #         max-interval: 30s
  #       default-requeue-rejected: false
  #       concurrency: 5
  #       max-concurrency: 10
  #       prefetch: 10
  #       acknowledge-mode: auto
  #   publisher-confirm-type: correlated
  #   publisher-returns: true
    
  # KAFKA CONFIGURATION - TEMPORARILY DISABLED
  # kafka:
  #   bootstrap-servers: ${KAFKA_BOOTSTRAP_SERVERS:localhost:9092}
  #   consumer:
  #     group-id: social-media-manager
  #     auto-offset-reset: earliest
  #     key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
  #     value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
  #     properties:
  #       spring.json.trusted.packages: "com.social.media"
  #   producer:
  #     key-serializer: org.apache.kafka.common.serialization.StringSerializer
  #     value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
  #     acks: all
  #     retries: 3
      
  # ============================================
  # SECURITY CONFIGURATION
  # ============================================
  security:
    oauth2:
      client:
        registration:
          instagram:
            client-id: ${INSTAGRAM_CLIENT_ID:}
            client-secret: ${INSTAGRAM_CLIENT_SECRET:}
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            scope: user_profile,user_media
          facebook:
            client-id: ${FACEBOOK_CLIENT_ID:}
            client-secret: ${FACEBOOK_CLIENT_SECRET:}
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            scope: pages_manage_posts,pages_read_engagement
          linkedin:
            client-id: ${LINKEDIN_CLIENT_ID:}
            client-secret: ${LINKEDIN_CLIENT_SECRET:}
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            scope: r_liteprofile,w_member_social
        provider:
          instagram:
            authorization-uri: https://api.instagram.com/oauth/authorize
            token-uri: https://api.instagram.com/oauth/access_token
            user-info-uri: https://graph.instagram.com/me
          facebook:
            authorization-uri: https://www.facebook.com/v18.0/dialog/oauth
            token-uri: https://graph.facebook.com/v18.0/oauth/access_token
            user-info-uri: https://graph.facebook.com/me
          linkedin:
            authorization-uri: https://www.linkedin.com/oauth/v2/authorization
            token-uri: https://www.linkedin.com/oauth/v2/accessToken
            user-info-uri: https://api.linkedin.com/v2/people/~
            
  # ============================================
  # CACHE CONFIGURATION
  # ============================================
  cache:
    type: caffeine
    caffeine:
      spec: maximumSize=10000,expireAfterWrite=30m,recordStats
    cache-names:
      - userProfiles
      - socialAccounts
      - hashtags
      - metrics
      - campaigns
      
  # ============================================
  # QUARTZ SCHEDULER - TEMPORARILY DISABLED
  # ============================================
  # quartz:
  #   job-store-type: jdbc
  #   properties:
  #     org:
  #       quartz:
  #         scheduler:
  #           instanceName: SocialMediaManagerScheduler
  #           instanceId: AUTO
  #         jobStore:
  #           class: org.quartz.impl.jdbcjobstore.JobStoreTX
  #           driverDelegateClass: org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
  #           useProperties: false
  #           misfireThreshold: 60000
  #           tablePrefix: QRTZ_
  #           isClustered: true
  #           clusterCheckinInterval: 10000
  #         threadPool:
  #           class: org.quartz.simpl.SimpleThreadPool
  #           threadCount: 10
  #           threadPriority: 5
  #           threadsInheritContextClassLoaderOfInitializingThread: true

# ============================================
# AXON FRAMEWORK CONFIGURATION (CQRS/Event Sourcing) - COMPLETELY DISABLED
# ============================================
# axon:
#   axonserver:
#     enabled: false

# ============================================
# RESILIENCE4J CONFIGURATION
# ============================================
resilience4j:
  circuitbreaker:
    configs:
      default:
        register-health-indicator: true
        sliding-window-size: 20
        minimum-number-of-calls: 10
        permitted-number-of-calls-in-half-open-state: 5
        wait-duration-in-open-state: 30s
        failure-rate-threshold: 50
        slow-call-rate-threshold: 50
        slow-call-duration-threshold: 3s
        automatic-transition-from-open-to-half-open-enabled: true
    instances:
      instagram-api:
        base-config: default
        slow-call-duration-threshold: 2s
      facebook-api:
        base-config: default
        slow-call-duration-threshold: 2s
      twitter-api:
        base-config: default
        slow-call-duration-threshold: 2s
      linkedin-api:
        base-config: default
        slow-call-duration-threshold: 3s
        
  retry:
    configs:
      default:
        max-attempts: 3
        wait-duration: 1s
        exponential-backoff-multiplier: 2
        exponential-max-wait-duration: 10s
        retry-exceptions:
          - java.net.SocketTimeoutException
          - java.io.IOException
          - org.springframework.web.client.ResourceAccessException
    instances:
      instagram-api:
        base-config: default
      facebook-api:
        base-config: default
      twitter-api:
        base-config: default
      linkedin-api:
        base-config: default
        
  timelimiter:
    configs:
      default:
        timeout-duration: 5s
        cancel-running-future: true
    instances:
      instagram-api:
        base-config: default
        timeout-duration: 3s
      facebook-api:
        base-config: default
        timeout-duration: 3s
      twitter-api:
        base-config: default
        timeout-duration: 3s
      linkedin-api:
        base-config: default
        timeout-duration: 5s
        
  bulkhead:
    configs:
      default:
        max-concurrent-calls: 10
        max-wait-duration: 2s
    instances:
      social-media-apis:
        base-config: default
        max-concurrent-calls: 25

# ============================================
# SECURITY CONFIGURATION
# ============================================
security:
  jwt:
    secret: ${JWT_SECRET:${random.value}}
    issuer: social-media-manager
    audience: social-media-manager-users
    expiration: ${JWT_EXPIRATION:86400000} # 24 hours
    refresh-expiration: ${JWT_REFRESH_EXPIRATION:604800000} # 7 days
    
  cors:
    allowed-origins: ${CORS_ALLOWED_ORIGINS:http://localhost:3000,http://localhost:4200}
    allowed-methods: GET,POST,PUT,DELETE,PATCH,OPTIONS
    allowed-headers: "*"
    allow-credentials: true
    max-age: 3600
    
  rate-limiting:
    enabled: ${RATE_LIMITING_ENABLED:true}
    global:
      capacity: 1000
      refill-period: 1h
    per-user:
      capacity: 100
      refill-period: 1h
    per-api:
      capacity: 50
      refill-period: 1m

# ============================================
# ACTUATOR & MONITORING
# ============================================
management:
  endpoints:
    web:
      exposure:
        include: health,metrics,prometheus,info,circuitbreakers,ratelimiters,caches,scheduledtasks,loggers,auditevents,httptrace
      base-path: /actuator
      cors:
        allowed-origins: "*"
        allowed-methods: GET,POST
  endpoint:
    health:
      show-details: always
      show-components: always
      probes:
        enabled: true
    metrics:
      enabled: true
    prometheus:
      enabled: true
    shutdown:
      enabled: false
  metrics:
    distribution:
      percentiles-histogram:
        http.server.requests: true
        spring.data.repository.invocations: true
      percentiles:
        http.server.requests: 0.5, 0.9, 0.95, 0.99
        spring.data.repository.invocations: 0.5, 0.9, 0.95, 0.99
    tags:
      application: ${spring.application.name}
  health:
    circuitbreakers:
      enabled: true
    ratelimiters:
      enabled: true
    diskspace:
      enabled: true
      threshold: 1GB
    redis:
      enabled: false  # Disabled until Redis is properly configured
    db:
      enabled: true
    rabbit:
      enabled: false  # Disabled until RabbitMQ is properly configured
    mongo:
      enabled: false  # Disabled until MongoDB is properly configured
  prometheus:
    metrics:
      export:
        enabled: true
        step: 30s
  tracing:
    enabled: false
    sampling:
      probability: 0.0

# ============================================
# LOGGING CONFIGURATION
# ============================================
logging:
  level:
    com.social.media: ${LOG_LEVEL:INFO}
    org.springframework.security: ${SECURITY_LOG_LEVEL:WARN}
    org.springframework.data.jpa: ${JPA_LOG_LEVEL:WARN}
    org.hibernate.SQL: ${SQL_LOG_LEVEL:WARN}
    org.hibernate.orm.jdbc.bind: ${SQL_PARAM_LOG_LEVEL:WARN}
    io.github.resilience4j: ${RESILIENCE_LOG_LEVEL:INFO}
    org.springframework.amqp: ${AMQP_LOG_LEVEL:WARN}
    org.springframework.kafka: ${KAFKA_LOG_LEVEL:WARN}
    org.springframework.cache: ${CACHE_LOG_LEVEL:WARN}
    io.micrometer: ${MICROMETER_LOG_LEVEL:WARN}
  pattern:
    console: "%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"
    file: "%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"
  file:
    name: ${LOG_FILE_PATH:./logs/social-media-manager.log}
    max-size: 100MB
    max-history: 30
  logback:
    rollingpolicy:
      max-file-size: 100MB
      max-history: 30
      total-size-cap: 1GB

# ============================================
# APPLICATION SPECIFIC CONFIGURATION
# ============================================
app:
  # BUSINESS RULES
  business:
    max-users-per-company: ${MAX_USERS_PER_COMPANY:50}
    max-social-accounts-per-user: ${MAX_SOCIAL_ACCOUNTS_PER_USER:10}
    max-posts-per-day: ${MAX_POSTS_PER_DAY:100}
    max-campaigns-per-company: ${MAX_CAMPAIGNS_PER_COMPANY:20}
    max-bots-per-company: ${MAX_BOTS_PER_COMPANY:10}
    
  # AUTOMATION SETTINGS
  automation:
    default-bot-interval-seconds: ${DEFAULT_BOT_INTERVAL:60}
    max-actions-per-hour: ${MAX_ACTIONS_PER_HOUR:50}
    max-actions-per-day: ${MAX_ACTIONS_PER_DAY:1000}
    respect-rate-limits: ${RESPECT_RATE_LIMITS:true}
    simulate-human-behavior: ${SIMULATE_HUMAN_BEHAVIOR:true}
    
  # EXTERNAL API CONFIGURATION
  external-apis:
    timeout-seconds: ${API_TIMEOUT:10}
    max-retries: ${API_MAX_RETRIES:3}
    connection-pool-size: ${API_CONNECTION_POOL_SIZE:20}
    
    # Social Network API Limits
    instagram:
      requests-per-hour: ${INSTAGRAM_REQUESTS_PER_HOUR:4000}
      requests-per-day: ${INSTAGRAM_REQUESTS_PER_DAY:48000}
      posts-per-hour: ${INSTAGRAM_POSTS_PER_HOUR:25}
      
    facebook:
      requests-per-hour: ${FACEBOOK_REQUESTS_PER_HOUR:4800}
      requests-per-day: ${FACEBOOK_REQUESTS_PER_DAY:57600}
      posts-per-hour: ${FACEBOOK_POSTS_PER_HOUR:30}
      
    twitter:
      requests-per-hour: ${TWITTER_REQUESTS_PER_HOUR:1500}
      requests-per-day: ${TWITTER_REQUESTS_PER_DAY:36000}
      posts-per-hour: ${TWITTER_POSTS_PER_HOUR:15}
      
    linkedin:
      requests-per-hour: ${LINKEDIN_REQUESTS_PER_HOUR:1000}
      requests-per-day: ${LINKEDIN_REQUESTS_PER_DAY:24000}
      posts-per-hour: ${LINKEDIN_POSTS_PER_HOUR:20}
    
  # CACHING CONFIGURATION
  cache:
    user-profiles-ttl: ${USER_PROFILES_CACHE_TTL:3600} # 1 hour
    social-accounts-ttl: ${SOCIAL_ACCOUNTS_CACHE_TTL:1800} # 30 minutes
    hashtags-ttl: ${HASHTAGS_CACHE_TTL:7200} # 2 hours
    metrics-ttl: ${METRICS_CACHE_TTL:300} # 5 minutes
    campaigns-ttl: ${CAMPAIGNS_CACHE_TTL:1800} # 30 minutes
    
  # ANALYTICS CONFIGURATION
  analytics:
    batch-size: ${ANALYTICS_BATCH_SIZE:500}
    processing-interval-minutes: ${ANALYTICS_INTERVAL:5}
    retention-days: ${ANALYTICS_RETENTION_DAYS:365}
    real-time-processing: ${REAL_TIME_ANALYTICS:true}
    
  # FILE UPLOAD CONFIGURATION
  file-upload:
    max-file-size: ${MAX_FILE_SIZE:50MB}
    max-request-size: ${MAX_REQUEST_SIZE:100MB}
    allowed-extensions: jpg,jpeg,png,gif,mp4,mov,avi,pdf,doc,docx
    storage-path: ${UPLOAD_STORAGE_PATH:./uploads}
    
  # NOTIFICATION CONFIGURATION
  notifications:
    email:
      enabled: ${EMAIL_NOTIFICATIONS_ENABLED:true}
      from: ${EMAIL_FROM:noreply@socialmanager.com}
      templates-path: ${EMAIL_TEMPLATES_PATH:classpath:/templates/email}
    push:
      enabled: ${PUSH_NOTIFICATIONS_ENABLED:false}
    webhook:
      enabled: ${WEBHOOK_NOTIFICATIONS_ENABLED:true}
      timeout-seconds: ${WEBHOOK_TIMEOUT:10}
      
  # FEATURE FLAGS
  features:
    ai-content-generation: ${FEATURE_AI_CONTENT:false}
    advanced-analytics: ${FEATURE_ADVANCED_ANALYTICS:true}
    multi-tenancy: ${FEATURE_MULTI_TENANCY:true}
    api-versioning: ${FEATURE_API_VERSIONING:true}
    event-sourcing: ${FEATURE_EVENT_SOURCING:true}

# ============================================
# SPRINGDOC OPENAPI CONFIGURATION
# ============================================
springdoc:
  api-docs:
    path: /v3/api-docs
    enabled: true
    groups:
      enabled: true
  swagger-ui:
    path: /swagger-ui.html
    enabled: true
    tags-sorter: alpha
    operations-sorter: alpha
    try-it-out-enabled: true
    filter: true
    display-request-duration: true
    doc-expansion: none
    deep-linking: true
    show-extensions: true
    show-common-extensions: true
  show-actuator: true
  group-configs:
    - group: public-api
      paths-to-match: /api/v1/public/**
      packages-to-scan: com.social.media.interfaces.rest.public
    - group: admin-api
      paths-to-match: /api/v1/admin/**
      packages-to-scan: com.social.media.interfaces.rest.admin
    - group: user-api
      paths-to-match: /api/v1/user/**
      packages-to-scan: com.social.media.interfaces.rest.user

# ============================================
# SINGLE CONFIGURATION - NO PROFILES
# ============================================