import express from 'express';
import publicationsRouter from './routes/publications.js';
import searchRouter from './routes/search.js';
import { runScheduledPublish } from './lib/scheduler.js';

const app = express();
const PORT = process.env.PORT || 4001;

app.use(express.json({ limit: '10mb' }));

// API публикаций
app.use('/api/publications', publicationsRouter);

// Алиас /api/posts -> publications (обратная совместимость)
app.use('/api/posts', (req, res, next) => {
  const origJson = res.json.bind(res);
  res.json = (body: unknown) => {
    if (body && typeof body === 'object' && 'publications' in body) {
      return origJson({ ...body, posts: (body as any).publications });
    }
    return origJson(body);
  };
  next();
}, publicationsRouter);

// SearXNG JSON Engine — поиск по опубликованным
app.use('/search', searchRouter);

// Health
app.get('/health', (_, res) => res.json({ status: 'ok' }));

// Планировщик: каждую минуту проверяет и публикует запланированные
setInterval(runScheduledPublish, 60_000);
runScheduledPublish();

app.listen(PORT, () => {
  console.log(`Publications Service: http://localhost:${PORT}`);
  console.log(`  API:        /api/publications`);
  console.log(`  Calendar:   /api/publications/calendar`);
  console.log(`  SearXNG:    /search?q=...`);
});
