/**
 * Multi-Domain Routing Middleware
 * 
 * Routes custom domains (aesthetichelp.com) to pages from database.
 * Uses Redis caching for <5ms performance.
 * 
 * Flow:
 * 1. Extract domain from Host header
 * 2. Lookup site by domain (Redis cached)
 * 3. Lookup page by route (Redis cached)
 * 4. Rewrite to dynamic renderer
 */
import { defineMiddleware } from 'astro:middleware';
import { pool } from '@/lib/db';
import { getCached } from '@/lib/cache/redis';

export const onRequest = defineMiddleware(async (context, next) => {
    const host = context.request.headers.get('host')?.split(':')[0].replace(/^www\./, '') || '';
    const pathname = context.url.pathname;

    // Skip static assets, admin, API routes
    if (
        pathname.startsWith('/admin') ||
        pathname.startsWith('/api') ||
        pathname.startsWith('/shim') ||
        pathname.startsWith('/preview') ||
        pathname.startsWith('/render') ||
        pathname.match(/\.(ico|png|jpg|jpeg|svg|css|js|woff|woff2|map|html|webp|gif|pdf)$/)
    ) {
        return next();
    }

    // Platform domain - allow default routing
    const platformDomain = import.meta.env.PUBLIC_PLATFORM_DOMAIN || 'spark.jumpstartscaling.com';
    if (host.includes(platformDomain) || host === 'localhost' || host === '127.0.0.1') {
        return next();
    }

    try {
        // ⚡ REDIS-CACHED SITE LOOKUP (5 min cache)
        const site = await getCached(
            `site:${host}:meta`,
            async () => {
                const { rows } = await pool.query(
                    'SELECT id, name, domain, status, config FROM sites WHERE domain = $1',
                    [host]
                );
                return rows[0] || null;
            },
            300 // 5 min cache
        );

        if (!site) {
            return new Response(`
                <!DOCTYPE html>
                <html>
                <head><title>Site Not Found</title></head>
                <body style="font-family: system-ui; text-align: center; padding: 100px 20px;">
                    <h1>🔍 Site Not Found</h1>
                    <p>The domain <strong>${host}</strong> is not configured.</p>
                    <p style="color: #666; font-size: 14px;">
                        Please contact support if you believe this is an error.
                    </p>
                </body>
                </html>
            `, {
                status: 404,
                headers: { 'Content-Type': 'text/html' }
            });
        }

        if (site.status !== 'active') {
            return new Response(`
                <!DOCTYPE html>
                <html>
                <head><title>Site Maintenance</title></head>
                <body style="font-family: system-ui; text-align: center; padding: 100px 20px;">
                    <h1>🚧 Site Under Maintenance</h1>
                    <p>We'll be back soon!</p>
                </body>
                </html>
            `, {
                status: 503,
                headers: { 'Content-Type': 'text/html' }
            });
        }

        // Inject site data into context
        context.locals.site = site;
        context.locals.siteId = site.id;

        // ⚡ REDIS-CACHED PAGE LOOKUP (1 min cache)
        const page = await getCached(
            `site:${host}:page:${pathname}`,
            async () => {
                const { rows } = await pool.query(
                    `SELECT * FROM pages 
                     WHERE site_id = $1 AND route = $2 AND status = 'published'
                     LIMIT 1`,
                    [site.id, pathname]
                );
                return rows[0] || null;
            },
            60 // 1 min cache
        );

        if (page) {
            context.locals.page = page;
            return context.rewrite('/render/page');
        }

        // Check for blog post (route: /blog/post-slug)
        if (pathname.startsWith('/blog/')) {
            const slug = pathname.replace('/blog/', '');

            const post = await getCached(
                `site:${host}:post:${slug}`,
                async () => {
                    const { rows } = await pool.query(
                        `SELECT * FROM posts 
                         WHERE site_id = $1 AND slug = $2 AND status = 'published'
                         LIMIT 1`,
                        [site.id, slug]
                    );
                    return rows[0] || null;
                },
                60
            );

            if (post) {
                context.locals.post = post;
                return context.rewrite('/render/post');
            }
        }

        // 404 - check for custom 404 page
        const notFoundPage = await getCached(
            `site:${host}:page:/404`,
            async () => {
                const { rows } = await pool.query(
                    `SELECT * FROM pages 
                     WHERE site_id = $1 AND route = '/404'
                     LIMIT 1`,
                    [site.id]
                );
                return rows[0] || null;
            },
            300
        );

        if (notFoundPage) {
            context.locals.page = notFoundPage;
            return context.rewrite('/render/page');
        }

        // Default 404
        return new Response(`
            <!DOCTYPE html>
            <html>
            <head><title>Page Not Found</title></head>
            <body style="font-family: system-ui; text-align: center; padding: 100px 20px;">
                <h1>404 - Page Not Found</h1>
                <p>The page <strong>${pathname}</strong> doesn't exist.</p>
                <a href="/" style="color: #667eea;">← Back to Home</a>
            </body>
            </html>
        `, {
            status: 404,
            headers: { 'Content-Type': 'text/html' }
        });

    } catch (err) {
        console.error('Middleware error:', err);
        return new Response('Internal Server Error', { status: 500 });
    }
});
