// 绑定流程 — 二维码扫描后的绑定页面和绑定操作
// QR 码内容：{HERMES_BASE_URL}/api/bind/{profileId}
// 扫描后展示绑定页面，用户确认绑定

const express = require('express');
const { getProfileMeta, bindWechat } = require('../lib/profile-store');

const router = express.Router();

// 绑定页面（GET）— 扫描二维码后打开
router.get('/:profileId', (req, res) => {
  try {
    const meta = getProfileMeta(req.params.profileId);
    if (!meta) {
      // P3 修复：返回 404 状态码
      return res.status(404).type('html').send(renderNotFoundPage());
    }

    // 如果已绑定，显示已绑定页面
    if (meta.boundWechat) {
      return res.type('html').send(renderAlreadyBoundPage(meta));
    }

    // 显示绑定确认页面
    res.type('html').send(renderBindPage(meta));
  } catch (err) {
    // P2 修复：异常时返回 HTML 而非 JSON
    console.error('绑定页面加载失败:', err);
    res.status(500).type('html').send(renderNotFoundPage());
  }
});

// 执行绑定（POST）
router.post('/:profileId', (req, res) => {
  try {
    const meta = getProfileMeta(req.params.profileId);
    if (!meta) {
      return res.status(404).json({ error: 'Profile 不存在' });
    }
    if (meta.boundWechat) {
      return res.status(400).json({ error: '该 Profile 已绑定微信' });
    }

    // P2 修复：req.body 可能为 undefined
    const body = req.body || {};
    // 绑定标识：优先用微信 OAuth code，其次用请求体中的 wechatId
    // 实际生产环境中，这里应通过微信 OAuth 获取 openid
    const wechatId = body.wechatId || body.openid;

    if (!wechatId) {
      return res.status(400).json({ error: '缺少 wechatId，请通过微信 OAuth 授权' });
    }

    // P1 修复：bindWechat 内部有原子检查，处理 alreadyBound 返回
    const result = bindWechat(req.params.profileId, wechatId);
    if (!result) {
      return res.status(404).json({ error: 'Profile 不存在' });
    }
    if (result.alreadyBound) {
      return res.status(400).json({ error: '该 Profile 已被绑定' });
    }

    console.log(`[Hermes] Profile ${req.params.profileId} 已绑定微信: ${wechatId}`);

    res.json({
      message: '绑定成功',
      profileId: result.profileId,
      profileName: result.profileName,
      boundAt: result.boundAt,
    });
  } catch (err) {
    console.error('绑定失败:', err);
    res.status(500).json({ error: '绑定失败' });
  }
});

// ===== HTML 页面渲染 =====

function renderBindPage(meta) {
  // P3 修复：profileId 在 form action 中转义
  const safeProfileId = encodeURIComponent(meta.profileId);
  return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>绑定角色 - ${escapeHtml(meta.profileName)}</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #f5f5f5; color: #333; }
    .container { max-width: 400px; margin: 0 auto; padding: 24px 20px; min-height: 100vh; display: flex; flex-direction: column; justify-content: center; }
    .card { background: #fff; border-radius: 16px; padding: 32px 24px; box-shadow: 0 2px 12px rgba(0,0,0,0.08); text-align: center; }
    .avatar { width: 72px; height: 72px; border-radius: 50%; background: linear-gradient(135deg, #667eea, #764ba2); margin: 0 auto 16px; display: flex; align-items: center; justify-content: center; font-size: 32px; color: #fff; }
    h1 { font-size: 20px; margin-bottom: 8px; }
    .desc { font-size: 14px; color: #888; margin-bottom: 24px; line-height: 1.6; }
    .info { background: #f8f8f8; border-radius: 8px; padding: 12px 16px; margin-bottom: 24px; text-align: left; }
    .info-row { display: flex; justify-content: space-between; font-size: 13px; padding: 4px 0; }
    .info-label { color: #999; }
    .info-value { color: #333; font-weight: 500; }
    .btn { width: 100%; padding: 14px; border: none; border-radius: 12px; background: #07c160; color: #fff; font-size: 16px; font-weight: 600; cursor: pointer; transition: opacity 0.2s; }
    .btn:active { opacity: 0.8; }
    .footer { text-align: center; margin-top: 16px; font-size: 12px; color: #bbb; }
  </style>
</head>
<body>
  <div class="container">
    <div class="card">
      <div class="avatar">${escapeHtml(meta.profileName.charAt(0))}</div>
      <h1>${escapeHtml(meta.profileName)}</h1>
      <p class="desc">扫描绑定后，即可在微信中与该角色对话</p>
      <div class="info">
        <div class="info-row"><span class="info-label">Profile ID</span><span class="info-value">${escapeHtml(meta.profileId)}</span></div>
        <div class="info-row"><span class="info-label">创建时间</span><span class="info-value">${new Date(meta.createdAt).toLocaleString('zh-CN')}</span></div>
        <div class="info-row"><span class="info-label">状态</span><span class="info-value" style="color:#07c160">待绑定</span></div>
      </div>
      <form method="POST" action="/api/bind/${safeProfileId}">
        <input type="hidden" name="wechatId" value="wechat_oauth_placeholder">
        <button type="submit" class="btn">确认绑定</button>
      </form>
      <div class="footer">Hermes Server</div>
    </div>
  </div>
</body>
</html>`;
}

function renderAlreadyBoundPage(meta) {
  return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>已绑定 - ${escapeHtml(meta.profileName)}</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #f5f5f5; color: #333; }
    .container { max-width: 400px; margin: 0 auto; padding: 24px 20px; min-height: 100vh; display: flex; flex-direction: column; justify-content: center; }
    .card { background: #fff; border-radius: 16px; padding: 32px 24px; box-shadow: 0 2px 12px rgba(0,0,0,0.08); text-align: center; }
    .icon { font-size: 48px; margin-bottom: 16px; }
    h1 { font-size: 20px; margin-bottom: 8px; }
    .desc { font-size: 14px; color: #888; margin-bottom: 16px; }
    .info { background: #f8f8f8; border-radius: 8px; padding: 12px 16px; text-align: left; }
    .info-row { display: flex; justify-content: space-between; font-size: 13px; padding: 4px 0; }
    .info-label { color: #999; }
    .info-value { color: #333; }
  </style>
</head>
<body>
  <div class="container">
    <div class="card">
      <div class="icon">✅</div>
      <h1>${escapeHtml(meta.profileName)}</h1>
      <p class="desc">该角色已成功绑定微信</p>
      <div class="info">
        <div class="info-row"><span class="info-label">绑定时间</span><span class="info-value">${new Date(meta.boundAt).toLocaleString('zh-CN')}</span></div>
        <div class="info-row"><span class="info-label">状态</span><span class="info-value" style="color:#07c160">已绑定</span></div>
      </div>
    </div>
  </div>
</body>
</html>`;
}

function renderNotFoundPage() {
  return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>角色不存在</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #f5f5f5; color: #333; }
    .container { max-width: 400px; margin: 0 auto; padding: 24px; min-height: 100vh; display: flex; align-items: center; justify-content: center; }
    .card { background: #fff; border-radius: 16px; padding: 32px; text-align: center; box-shadow: 0 2px 12px rgba(0,0,0,0.08); }
    .icon { font-size: 48px; margin-bottom: 16px; }
    h1 { font-size: 18px; color: #666; }
  </style>
</head>
<body>
  <div class="container">
    <div class="card">
      <div class="icon">🔍</div>
      <h1>角色不存在或二维码已失效</h1>
    </div>
  </div>
</body>
</html>`;
}

function escapeHtml(str) {
  return String(str).replace(/[&<>"']/g, (c) => ({
    '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
  }[c]));
}

module.exports = router;
