import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { generatePosts, IPostCardProps } from './data';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const page = parseInt(searchParams.get('page') || '1', 10);
  const limit = parseInt(searchParams.get('limit') || '6', 10);
  const lang = (await cookies()).get('lang')?.value || 'fa';

  let posts = generatePosts();

  let data: IPostCardProps[] = posts.map(
    ({ id, title, fa_title, imageSrc, link }) => ({
      id,
      title: lang === 'fa' && fa_title ? fa_title : title,
      imageSrc,
      link,
    }),
  );

  const totalItems = data.length;
  const totalPages = Math.ceil(totalItems / limit);
  const startIndex = (page - 1) * limit;
  const endIndex = startIndex + limit;
  const paginatedData = data.slice(startIndex, endIndex);

  return NextResponse.json({
    data: paginatedData,
    pagination: {
      currentPage: page,
      totalPages,
      totalItems,
      limit,
    },
  });
}
