// config/middlewares.ts

// Helper function to get allowed origins based on environment
// Ensures required domains are always included
const getAllowedOrigins = () => {
  const allowedOrigins = [
    'https://genomii.ai', // Your production frontend **REQUIRED**
    // Add other domains if needed, e.g., staging environments
  ];

  // Optionally add localhost for development environments
  if (process.env.NODE_ENV !== 'production') {
    allowedOrigins.push('http://localhost:3000'); // Common React dev port
    allowedOrigins.push('http://localhost:1337'); // Strapi default admin port
  }
  
  // Include the Strapi server URL itself if necessary for admin panel or previews
  if (process.env.URL) {
     allowedOrigins.push(process.env.URL); // URL Strapi is running on (e.g., https://strapi.genomii.ai)
  } else {
    // Fallback if URL env var isn't set (adjust if needed)
    allowedOrigins.push('https://strapi.genomii.ai'); 
  }

  return allowedOrigins;
};


export default [
  'strapi::logger',
  'strapi::errors',
  {
    name: 'strapi::security',
    config: {
      contentSecurityPolicy: {
        useDefaults: true,
        directives: {
          // Your existing CSP directives... make sure CLOUDFRONT_URL is properly set in your environment
          'connect-src': ["'self'", 'https:'], 
          'img-src': [
            "'self'",
            'data:',
            'blob:',
            'https://market-assets.strapi.io',
            `https://${process.env.AWS_BUCKET}.s3.${process.env.AWS_REGION}.amazonaws.com`, // Use env vars for bucket
            '*.s3.amazonaws.com', // More general S3 pattern if needed
            process.env.CLOUDFRONT_URL || 'https://blog-media.genomii.ai', // CloudFront domain
          ],
          'media-src': [
            "'self'",
            'data:',
            'blob:',
            'https://market-assets.strapi.io',
            `https://${process.env.AWS_BUCKET}.s3.${process.env.AWS_REGION}.amazonaws.com`, // Use env vars for bucket
            '*.s3.amazonaws.com', // More general S3 pattern if needed
            process.env.CLOUDFRONT_URL || 'https://blog-media.genomii.ai', // CloudFront domain
          ],
          upgradeInsecureRequests: null,
        },
      },
    },
  },
  // == Replace 'strapi::cors' with this configuration object ==
  {
    name: 'strapi::cors',
    config: {
      enabled: true,
      headers: '*', // Allow all headers, or specify ['Content-Type', 'Authorization', ...]
      origin: getAllowedOrigins(), // Dynamically set allowed origins
      methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'], // Common methods needed
      credentials: false // Set to true if you need cookies/auth headers across origins
    }
  },
  // ==========================================================
  'strapi::poweredBy',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
];