const fs = require('fs');
const https = require('https');
const express = require('express');
const cors = require('cors');
const webpush = require('web-push');   // ← 追加

const app = express();

app.use(cors({
  origin: 'https://10.0.0.20:5173',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type'],
  credentials: true
}));
app.use(express.json());

// ===== VAPIDキー設定（ここにあなたが生成した鍵を入れる） =====
const VAPID_PUBLIC_KEY = 'BD7GhguZw4c_omQrJ9NHVoF9nrVbTijg7-Kb33F8oZKZ4HPh5eVVXZQObsG1-yjJ2pkD24TIM8D9p3Jz7ZjFHj8';
const VAPID_PRIVATE_KEY = 's8r2Bgxh04m5NXd7ur3WB41PREqgYJ0D3sxrZrJuP-g';

webpush.setVapidDetails(
  'mailto:IotaAwoi@outlook.jp',   // 形式上のメールアドレス
  VAPID_PUBLIC_KEY,
  VAPID_PRIVATE_KEY
);

const SUBS_FILE = 'subscriptions.json';

// ===== 購読保存API =====
app.post('/api/subscribe', (req, res) => {
  const subscription = req.body;
  console.log('📩 Subscription received:', subscription);

  let subs = [];
  if (fs.existsSync(SUBS_FILE)) {
    subs = JSON.parse(fs.readFileSync(SUBS_FILE, 'utf-8'));
  }

  const exists = subs.some(sub => sub.endpoint === subscription.endpoint);
  if (!exists) {
    subs.push(subscription);
    fs.writeFileSync(SUBS_FILE, JSON.stringify(subs, null, 2));
  }

  res.status(201).json({ message: '購読情報を保存しました' });
});

// ===== 通知送信用API =====
app.post('/api/send', async (req, res) => {
  const { title, body } = req.body;

  if (!fs.existsSync(SUBS_FILE)) {
    return res.json({ results: [] });
  }

  const subs = JSON.parse(fs.readFileSync(SUBS_FILE, 'utf-8'));
  const payload = JSON.stringify({ title, body });

  const results = [];
  for (const sub of subs) {
    try {
      await webpush.sendNotification(sub, payload);
      results.push({ status: 'ok' });
    } catch (err) {
      console.error('❌ 通知送信エラー:', err);
      results.push({ status: 'rejected', reason: err.message });
    }
  }

  res.json({ results });
});

// ===== サーバー起動 =====
const options = {
  key: fs.readFileSync('C:/Users/monak/certs/server.key'),
  cert: fs.readFileSync('C:/Users/monak/certs/server.crt'),
};

https.createServer(options, app).listen(4000, '0.0.0.0', () => {
  console.log('🚀 Server running on https://10.0.0.20:4000');
});
