import { Router } from 'express';
import { db } from '../db/index.js';
import { publications } from '../db/schema.js';
import { sql } from 'drizzle-orm';
import { blocksToSearchText } from '../lib/content.js';

const router = Router();

/** Только опубликованные или запланированные (когда время наступило) */
function getPublishedItems() {
  const now = new Date().toISOString();
  const items = db
    .select()
    .from(publications)
    .where(
      sql`(${publications.status} = 'published' OR (${publications.status} = 'scheduled' AND ${publications.scheduledAt} <= ${now}))`,
    )
    .all();
  return items.sort((a, b) => {
    const da = a.publishedAt || a.scheduledAt || a.createdAt || '';
    const dbVal = b.publishedAt || b.scheduledAt || b.createdAt || '';
    return dbVal.localeCompare(da);
  });
}

// SearXNG JSON Engine API
router.get('/', (req, res) => {
  try {
    const query = (req.query.q as string)?.trim() || '';
    const pageno = Math.max(1, parseInt((req.query.page || req.query.pageno) as string) || 1);
    const pageSize = 10;
    const offset = (pageno - 1) * pageSize;

    const allItems = getPublishedItems();
    let filtered = allItems;
    if (query) {
      const q = query.toLowerCase();
      filtered = allItems.filter(
        (p) =>
          p.title?.toLowerCase().includes(q) ||
          (p.excerpt && p.excerpt.toLowerCase().includes(q)) ||
          p.url?.toLowerCase().includes(q) ||
          blocksToSearchText(p.contentBlocks).toLowerCase().includes(q),
      );
    }
    const items = filtered.slice(offset, offset + pageSize);

    const results = filtered.map((p) => ({
      url: p.url,
      title: p.title,
      content: (p.excerpt || blocksToSearchText(p.contentBlocks) || '').slice(0, 500),
      ...(p.author && { author: p.author }),
      ...(p.previewImage && { thumbnail: p.previewImage }),
    }));

    res.json({ results });
  } catch (e) {
    console.error(e);
    res.status(500).json({ results: [] });
  }
});

export default router;
