import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import {
  generateProjects,
  IProjectData,
  IProjectThumbResponseData,
} from './data';

export async function GET(request: Request) {
  let projects = generateProjects();
  let data = projects as IProjectThumbResponseData[];

  const cookieStore = await cookies();
  const lang = (await cookieStore).get('lang')?.value || 'fa';

  // Pagination logic
  const { searchParams } = new URL(request.url);

  const page = parseInt(searchParams.get('page') || '1', 10);
  const perPage = 6;

  const start = (page - 1) * perPage;
  const end = start + perPage;
  const paginatedProjects = projects.slice(start, end);

  const setRelatedLocaleData = (project: IProjectData) => ({
    title: project.fa_title || project.title,
  });

  data = paginatedProjects.map((project) => ({
    id: project.id,
    imageSrc: project.imageSrc,
    ...(lang === 'fa'
      ? setRelatedLocaleData(project)
      : { title: project.title }),
  }));

  return NextResponse.json({
    data,
    pagination: {
      page,
      perPage,
      total: projects.length,
      totalPages: Math.ceil(projects.length / perPage),
    },
  });
}
