// Express API for Redis/Valkey: keys list and single key fetch (for fast UI)
const express = require('express');
const Redis = require('ioredis');
const app = express();
const redis = new Redis({
  host: process.env.REDIS_HOST || '127.0.0.1',
  port: Number(process.env.REDIS_PORT || 6379),
  password: process.env.REDIS_PASSWORD,
});

// List all keys (no values)
app.get('/api/cache/keys', async (req, res) => {
  try {
    const keys = await redis.keys('*');
    // Optionally, add summary/metadata here
    res.json(keys.map(key => ({ key })));
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Fetch value for a single key
app.get('/api/cache/:key', async (req, res) => {
  try {
    const key = req.params.key;
    let value = await redis.get(key);
    try { value = JSON.parse(value); } catch {}
    res.json({ key, value });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

const port = process.env.CACHE_API_PORT || 3006;
app.listen(port, () => {
  console.log(`Cache API (keys+single) running on http://localhost:${port}/api/cache/keys`);
});
