import { Request, Response } from 'express';
import bookstackService from '../services/bookstack.service';
import environment from '../config/environment';
import logger from '../utils/logger';

class BookStackController {
  async getRecent(_req: Request, res: Response): Promise<void> {
    if (!environment.bookstack.url) {
      res.status(200).json({ success: true, data: [], configured: false });
      return;
    }
    try {
      const pages = await bookstackService.getRecentPages();
      res.status(200).json({ success: true, data: pages, configured: true });
    } catch (error) {
      logger.error('BookStackController.getRecent error', { error });
      res.status(500).json({ success: false, message: 'BookStack konnte nicht abgefragt werden' });
    }
  }

  async search(req: Request, res: Response): Promise<void> {
    if (!environment.bookstack.url) {
      res.status(200).json({ success: true, data: [], configured: false });
      return;
    }
    const query = req.query.query as string | undefined;
    if (!query || query.trim().length === 0) {
      res.status(400).json({ success: false, message: 'Suchbegriff fehlt' });
      return;
    }
    if (query.trim().length > 500) {
      res.status(400).json({ success: false, message: 'Suchanfrage zu lang' });
      return;
    }
    try {
      const results = await bookstackService.searchPages(query.trim());
      res.status(200).json({ success: true, data: results, configured: true });
    } catch (error) {
      logger.error('BookStackController.search error', { error });
      res.status(500).json({ success: false, message: 'BookStack-Suche fehlgeschlagen' });
    }
  }
  async getPage(req: Request, res: Response): Promise<void> {
    if (!environment.bookstack.url) {
      res.status(200).json({ success: true, data: null, configured: false });
      return;
    }
    const id = parseInt(String(req.params.id), 10);
    if (isNaN(id) || id <= 0) {
      res.status(400).json({ success: false, message: 'Ungültige Seiten-ID' });
      return;
    }
    try {
      const page = await bookstackService.getPageById(id);
      res.status(200).json({ success: true, data: page, configured: true });
    } catch (error) {
      logger.error('BookStackController.getPage error', { error });
      res.status(500).json({ success: false, message: 'BookStack-Seite konnte nicht geladen werden' });
    }
  }
}

export default new BookStackController();
