/**
 * Life Journey — Phase 0 deployment shell.
 *
 * This does the minimum needed to prove the plumbing works end to end:
 *   - serves the static frontend
 *   - answers GET /api/health   (is the server reachable?)
 *   - accepts a WebSocket on /ws (does WS survive the reverse proxy?)
 *
 * There is deliberately NO game logic here yet. Phase 1 adds the shared
 * game.js reducer, a SQLite-backed data model, rooms, and real actions.
 * The data directory is created now so the Docker volume mount is validated.
 */

import http from 'node:http';
import path from 'node:path';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import express from 'express';
import { WebSocketServer } from 'ws';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PORT = process.env.PORT || 3000;
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, '..', 'data');

// Ensure the persisted data directory exists (future: SQLite db + token uploads).
fs.mkdirSync(DATA_DIR, { recursive: true });

const app = express();
app.use(express.json());

// --- Health check: lets the frontend (and you) confirm the server is up ---
app.get('/api/health', (_req, res) => {
  res.json({
    ok: true,
    service: 'life-journey',
    phase: 0,
    version: '0.0.1',
    time: new Date().toISOString(),
  });
});

// --- Static frontend ---
const publicDir = path.join(__dirname, '..', 'public');
app.use(express.static(publicDir));

const server = http.createServer(app);

// --- WebSocket smoke test on /ws ---
// If this connects through your domain, Nginx Proxy Manager is passing the
// Upgrade/Connection headers correctly ("Websockets Support" is ON). Phase 1
// reuses this exact endpoint to push game state to each device.
const wss = new WebSocketServer({ server, path: '/ws' });
wss.on('connection', (ws) => {
  ws.send(JSON.stringify({ type: 'welcome', msg: 'WebSocket connected' }));
  ws.on('message', (raw) => {
    ws.send(JSON.stringify({ type: 'echo', received: raw.toString() }));
  });
});

server.listen(PORT, () => {
  console.log(`Life Journey (Phase 0) listening on :${PORT}`);
  console.log(`Data directory: ${DATA_DIR}`);
});
