const express = require('express');
const https = require('https');
const fs = require('fs');
const path = require('path');
const cookieParser = require('cookie-parser');

const app = express();
const PORT = 3443;

// 中间件
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 允许所有源
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
  });

// HTTPS配置
const httpsOptions = {
    key: fs.readFileSync(path.join(__dirname, 'certs', 'private-key.pem')),
    cert: fs.readFileSync(path.join(__dirname, 'certs', 'certificate.pem'))
};

// 根路由
app.get('/', (req, res) => {
    res.send(`
        <html>
        <head>
            <title>HTTPS Cookie 测试服务器</title>
            <meta charset="utf-8">
            <style>
                body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; }
                .btn { display: inline-block; padding: 10px 20px; margin: 5px; background: #007bff; color: white; text-decoration: none; border-radius: 5px; cursor: pointer; border: none; }
                .btn:hover { background: #0056b3; }
                .result { margin: 20px 0; padding: 15px; border-radius: 5px; }
                .success { background: #d4edda; border: 1px solid #c3e6cb; color: #155724; }
                .info { background: #d1ecf1; border: 1px solid #bee5eb; color: #0c5460; }
                .current-cookies { background: #f8f9fa; padding: 15px; border-radius: 5px; margin-top: 20px; }
            </style>
        </head>
        <body>
            <h1>HTTPS Cookie 测试服务器</h1>
            <p>服务器正在运行在 HTTPS 模式</p>
            
            <div>
                <button class="btn" onclick="setCookie()">设置Cookie (test=1, SameSite=None)</button>
                <button class="btn" onclick="getCookie()">获取Cookie</button>
                <button class="btn" onclick="clearCookie()">清除Cookie</button>
                <button class="btn" onclick="testApi()">测试API</button>
            </div>
            
            <div id="result"></div>
            
            <div class="current-cookies">
                <h3>当前页面Cookie:</h3>
                <p id="current-cookies">${JSON.stringify(req.cookies)}</p>
                <button class="btn" onclick="refreshCookies()">刷新Cookie显示</button>
            </div>

            <script>
                function showResult(data, type = 'info') {
                    const resultDiv = document.getElementById('result');
                    resultDiv.className = 'result ' + type;
                    resultDiv.innerHTML = '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
                }

                function updateCurrentCookies() {
                    const cookiesDiv = document.getElementById('current-cookies');
                    // 获取浏览器中的Cookie
                    const cookies = document.cookie.split(';').reduce((acc, cookie) => {
                        const [name, value] = cookie.trim().split('=');
                        if (name) acc[name] = value;
                        return acc;
                    }, {});
                    cookiesDiv.textContent = JSON.stringify(cookies);
                }

                async function setCookie() {
                    try {
                        const response = await fetch('/set-cookie');
                        const data = await response.json();
                        showResult(data, 'success');
                        updateCurrentCookies();
                    } catch (error) {
                        showResult({error: error.message}, 'error');
                    }
                }

                async function getCookie() {
                    try {
                        const response = await fetch('/get-cookie');
                        const data = await response.json();
                        showResult(data, 'info');
                    } catch (error) {
                        showResult({error: error.message}, 'error');
                    }
                }

                async function clearCookie() {
                    try {
                        const response = await fetch('/clear-cookie');
                        const data = await response.json();
                        showResult(data, 'success');
                        updateCurrentCookies();
                    } catch (error) {
                        showResult({error: error.message}, 'error');
                    }
                }

                async function testApi() {
                    try {
                        const response = await fetch('/api/test', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                message: '来自前端的测试消息',
                                timestamp: new Date().toISOString()
                            })
                        });
                        const data = await response.json();
                        showResult(data, 'success');
                    } catch (error) {
                        showResult({error: error.message}, 'error');
                    }
                }

                function refreshCookies() {
                    updateCurrentCookies();
                    getCookie();
                }

                // 页面加载时更新Cookie显示
                window.onload = function() {
                    updateCurrentCookies();
                };
            </script>
        </body>
        </html>
    `);
});

// 设置Cookie路由
app.get('/set-cookie', (req, res) => {
    // 设置Cookie: test=1, SameSite=None, Secure=true (HTTPS必需)
    res.cookie('test-none', '1', {
        sameSite: 'None',
        secure: true,  // HTTPS必需
        httpOnly: false, // 允许客户端JavaScript访问
        maxAge: 24 * 60 * 60 * 1000 // 24小时
    });

    res.cookie('test-lax', '1', {
        sameSite: 'Lax',
        secure: true,  // HTTPS必需
        httpOnly: false, // 允许客户端JavaScript访问
        maxAge: 24 * 60 * 60 * 1000 // 24小时
    });

    res.cookie('test-strict', '1', {
        sameSite: 'Strict',
        secure: true,  // HTTPS必需
        httpOnly: false, // 允许客户端JavaScript访问
        maxAge: 24 * 60 * 60 * 1000 // 24小时
    });

    res.json({
        message: 'Cookie已设置',
        cookie: {
            name: 'test',
            value: '1',
            sameSite: 'None',
            secure: true,
            httpOnly: false
        }
    });
});

// 获取Cookie路由
app.get('/get-cookie', (req, res) => {
    res.json({
        message: '当前所有Cookie',
        cookies: req.cookies,
        testCookie: req.cookies.test || '未设置'
    });
});

// 清除Cookie路由
app.get('/clear-cookie', (req, res) => {
    res.clearCookie('test', {
        sameSite: 'None',
        secure: true
    });
    
    res.json({
        message: 'Cookie已清除'
    });
});

// API路由示例
app.post('/api/test', (req, res) => {
    console.log('收到POST请求:', req.body);
    console.log('Cookie:', req.cookies);
    
    res.json({
        message: '请求处理成功',
        receivedData: req.body,
        cookies: req.cookies,
        timestamp: new Date().toISOString()
    });
});

// 错误处理
app.use((err, req, res, next) => {
    console.error('服务器错误:', err);
    res.status(500).json({
        error: '服务器内部错误',
        message: err.message
    });
});

// 启动HTTPS服务器
https.createServer(httpsOptions, app).listen(PORT, () => {
    console.log(`🚀 HTTPS服务器启动成功！`);
    console.log(`🔗 访问地址: https://localhost:${PORT}`);
    console.log(`📝 注意: 由于使用自签名证书，浏览器会显示安全警告，请选择"继续访问"`);
    console.log(`🍪 Cookie设置: test=1, SameSite=None, Secure=true`);
});

// 优雅关闭
process.on('SIGTERM', () => {
    console.log('收到SIGTERM信号，正在关闭服务器...');
    process.exit(0);
});

process.on('SIGINT', () => {
    console.log('收到SIGINT信号，正在关闭服务器...');
    process.exit(0);
}); 