import { defineConfig } from 'astro/config';
import dotenv from 'dotenv';
import node from '@astrojs/node';
import sitemap from '@astrojs/sitemap';

// Environment detection
const isProd = process.env.NODE_ENV === 'production';
dotenv.config();

export default defineConfig({
  site: 'https://juchatz.com', // Required for sitemap generation
  output: 'server', 
  
  adapter: node({
    mode: 'standalone'
  }),
  
  // Integrations
  integrations: [
    sitemap({
      changefreq: 'monthly',
      priority: 0.8,
      serialize(item) {
        // Homepage gets highest priority
        if (item.url === 'https://juchatz.com/' || item.url === 'https://juchatz.com') {
          item.priority = 1.0;
          item.changefreq = 'monthly';
        }
        // Main services page
        else if (item.url === 'https://juchatz.com/services/' || item.url === 'https://juchatz.com/services') {
          item.priority = 0.9;
          item.changefreq = 'monthly';
        }
        // Individual service pages
        else if (item.url.includes('/services/')) {
          item.priority = 0.8;
          item.changefreq = 'monthly';
        }
        // About page
        else if (item.url.includes('/about')) {
          item.priority = 0.8;
          item.changefreq = 'monthly'
        }
        // Contact page gets lower priority
        else if (item.url.includes('/contact')) {
          item.priority = 0.7;
          item.changefreq = 'monthly';
        }
        
        return item;
      },
      // Filter out API routes and other non-page URLs
      filter: (page) => !page.includes('/api/')
    })
  ],
  
  // Development server settings
  server: {
    host: '0.0.0.0',
    port: 4321,
    // Only allow local network in dev mode
    middleware: [
      // Middleware to check IP addresses
      (req, res, next) => {
        // Skip middleware in production
        if (isProd) return next();
        
        const clientIP = req.socket.remoteAddress || '';
        // Allow local IPs and 192.168.1.x
        if (
          clientIP === '127.0.0.1' || 
          clientIP === '::1' || 
          clientIP.startsWith('192.168.1.')
        ) {
          next();
        } else {
          res.statusCode = 403;
          res.end('Access denied: Your IP is not in the allowed range (192.168.1.0/24)');
        }
      }
    ]
  },
  
  // Vite configuration
  vite: {
    server: {
      // Allow domain for production
      allowedHosts: ['juchatz.com', 'www.juchatz.com'],
      
      // Production port (different from dev)
      hmr: {
        port: isProd ? 8080 : 4321
      }
    }
  }
});
