const express = require('express');
const router = express.Router();

import { Request, Response } from 'express';
import { requireLogin } from '../middleware/auth';
import { logger } from '../services/logging/logger';

// GET /welcome
router.get('/welcome', [requireLogin], async (req: Request, res: Response) => {
    const t0 = performance.now(); // optional profiling start

    try {
        const response = await fetch(`${process.env.DOC_HOST}/api/pages/717`, {
            headers: {
                Authorization: `Token ${process.env.DOC_TOKEN_ID}:${process.env.DOC_TOKEN_SECRET}`,
            },
        });

        if (!response.ok) {
            const text = await response.text();
            logger.error('app', 'Failed to fetch welcome page from Bookstack', {
                status: response.status,
                statusText: response.statusText,
                body: text,
                userId: req.user?.id,
            });
            return res.sendStatus(500);
        }

        const out = await response.json();
        res.status(200).json(out.html);

        // optional profiling log
        const duration = performance.now() - t0;
        logger.info(
            'profiling',
            'GET /welcome completed',
            {
                userId: req.user?.id,
                total_ms: duration,
            },
            'profiling'
        );

    } catch (error) {
        logger.error('app', 'Error fetching welcome page from Bookstack', {
            error: error instanceof Error ? error.message : String(error),
            stack: error instanceof Error ? error.stack : undefined,
            userId: req.user?.id,
        });
        res.sendStatus(500);
    }
});



export const docsRouter = router;