import { getFilteredBlogPosts } from '~~/lib/blog/read-posts';
import type { BlogPost } from '~~/lib/types/post';

export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const include = (content: BlogPost) => {
    const dateObj = new Date(content.date);

    if (query.year) {
      if (Number(query.year) !== dateObj.getFullYear()) {
        return false;
      }
    }

    if (query.month) {
      if (Number(query.month) !== dateObj.getMonth() + 1) {
        return false;
      }
    }

    if (query.day) {
      if (Number(query.day) !== dateObj.getDate()) {
        return false;
      }
    }

    if (query.tag) {
      const tags = Array.isArray(query.tag) ? query.tag : [query.tag];
      if (
        !content.tags?.length ||
        !tags.every((tag) => content.tags.includes(tag))
      ) {
        return false;
      }
    }

    return true;
  };

  const posts = await getFilteredBlogPosts(
    include,
    query.render !== 'false',
    query.body === 'true',
  );

  const limit = Number(query.limit) || 10;
  const pages = Math.ceil(posts.length / limit);
  const page = Math.max(Math.min(Number(query.page) || 1, pages), 1);
  const offset = (page - 1) * limit;

  if (pages > 1) {
    if (page + 1 <= pages) {
      appendResponseHeader(event, 'X-Next-Page', (page + 1).toString());
    }

    appendResponseHeader(event, 'X-Last-Page', pages.toString());
  }

  return posts.slice(offset, offset + limit);
});
