import { connection } from "@/lib/duckdb";
import type { NextApiRequest, NextApiResponse } from "next";

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse,
) {
    const { slug } = req.query;

    if (!slug || Array.isArray(slug)) {
        return res.status(400).json({ error: 'Invalid slug parameter' });
    }

    try {
        const result = await connection.run(`
            SELECT 
                *
            FROM wp_posts 
            WHERE post_name = $slug
            AND post_status = 'publish'
            AND post_type IN ('post', 'page')
            LIMIT 1;
        `, { slug: slug.toString() });

        const rows = await result.getRowObjectsJson();

        if (rows.length === 0) {
            return res.status(404).json({ error: 'Post not found' });
        }

        res.status(200).json(rows[0]);
    } catch (error) {
        console.error('Error fetching post:', error);
        res.status(500).json({ error: 'Failed to fetch post' });
    }
}