import type { APIRoute } from 'astro';
import PocketBase from 'pocketbase';

export const GET: APIRoute = async ({ params }) => {
  try {
    const pb = new PocketBase(import.meta.env.PB_POCKETBASE_URL);
    const { slug } = params;

    if (!slug) {
      return new Response(JSON.stringify({
        error: 'slug обязателен'
      }), { status: 400 });
    }

    const result = await pb.collection('posts').getList(1, 1, {
      filter: `slug="${slug}" && draft = false`,
    });

    if (result.totalItems === 0) {
      return new Response(JSON.stringify({
        error: 'Пост не найден'
      }), { status: 404 });
    }

    const post = result.items[0];

    return new Response(JSON.stringify({
      id: post.id,
      slug: post.slug,
      title: post.title,
      description: post.description,
      author: post.author,
      category: post.category,
      categoryColor: post.categoryColor,
      date: post.date,
      readTime: post.readTime,
      imageUrl: post.imageUrl,
      content: post.content,
    }), { status: 200 });

  } catch (error: any) {
    console.error('API post error:', error);

    return new Response(JSON.stringify({
      error: error.message || 'Ошибка при получении поста'
    }), { status: 500 });
  }
};