import { Hono } from 'hono';
import { createShade } from '@shade/sdk';

/**
 * __PROJECT_NAME__ — Shade-enabled Bun server template.
 *
 * Exposes two endpoints:
 *   POST /send     — encrypt a message to a peer
 *   POST /receive  — decrypt an incoming envelope
 */

const shade = await createShade({
  prekeyServer: process.env.SHADE_PREKEY_SERVER ?? '__PREKEY_SERVER__',
  storage: process.env.SHADE_DB_PATH ?? 'sqlite:./.shade/client.db',
  address: '__PROJECT_NAME__',
});

console.log(`Shade initialized as ${shade.myAddress}`);
console.log(`Fingerprint: ${await shade.fingerprint}`);

shade.onMessage((from, msg) => {
  console.log(`[${from}] ${msg}`);
});

// ─── Resumable-stream retention ──────────────────────────────────
//
// Drop stream-state records older than SHADE_STREAM_RETENTION_DAYS
// (default 14d). See docs/streams.md § Retention. Override the
// horizon with the env var; cron interval is fixed at 24h.
const STREAM_RETENTION_DAYS = Number(process.env.SHADE_STREAM_RETENTION_DAYS ?? 14);
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
const HORIZON_MS = STREAM_RETENTION_DAYS * ONE_DAY_MS;

async function pruneStreamStatesOnce(): Promise<void> {
  try {
    await shade.pruneStreamStates(Date.now() - HORIZON_MS);
  } catch (err) {
    console.error('[shade] pruneStreamStates failed:', err);
  }
}

await pruneStreamStatesOnce();
const streamPruneTimer = setInterval(pruneStreamStatesOnce, ONE_DAY_MS);
// Don't keep the process alive for the timer alone.
if (typeof streamPruneTimer.unref === 'function') streamPruneTimer.unref();

const app = new Hono();

app.get('/', (c) => c.text(`__PROJECT_NAME__ — Shade-enabled backend`));

app.post('/send', async (c) => {
  const { to, message } = await c.req.json();
  const envelope = await shade.send(to, message);
  return c.json({ envelope });
});

app.post('/receive', async (c) => {
  const { from, envelope } = await c.req.json();
  const plaintext = await shade.receive(from, envelope);
  return c.json({ plaintext });
});

export default {
  port: Number(process.env.PORT ?? 3000),
  fetch: app.fetch,
};

console.log(`Server listening on :${process.env.PORT ?? 3000}`);
