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

const PB_URL = import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090';

export const GET: APIRoute = async ({ url }) => {
  try {
    const pb = new PocketBase(PB_URL);

    const page = parseInt(url.searchParams.get('page') || '1');
    const perPage = parseInt(url.searchParams.get('per_page') || '10');
    const category = url.searchParams.get('category');
    const search = url.searchParams.get('search');

    const filter: string[] = ['draft = false'];

    if (category) {
      filter.push(`category = "${category}"`);
    }

    if (search) {
      filter.push(`(title ~ "${search}" || description ~ "${search}")`);
    }

    const result = await pb.collection('posts').getList(page, perPage, {
      filter: filter.join(' && '),
      sort: '-date',
    });

    const getImageUrl = (post: any) => {
      if (!post.image) return null;
      const fileUrl = pb.files.getUrl(post, post.image);
      if (fileUrl.startsWith('/')) {
        return `${PB_URL}${fileUrl}`;
      }
      return fileUrl;
    };

    return new Response(JSON.stringify({
      posts: result.items.map(post => ({
        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,
        image: getImageUrl(post),
      })),
      total: result.totalItems,
      page: result.page,
      perPage: result.perPage,
      totalPages: result.totalPages,
    }), { status: 200 });

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

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