import { NextRequest, NextResponse } from "next/server";
import prisma from "@/app/prisma";

interface QueryParams {
    currentPage: number;
    itemPerPage: number;
    search: string;
}

export async function GET(request: NextRequest) {
    const { searchParams } = request.nextUrl;
    const currentPage = Number(searchParams.get("currentPage")) || 1;
    const itemPerPage = Number(searchParams.get("itemPerPage")) || 1;
    const search = searchParams.get("search") || "";

    const skip = (currentPage - 1) * itemPerPage;  
    const take = itemPerPage;

    try {
        const sites = await prisma.site.findMany({
            skip,
            take,
            where: {
                name: {
                    contains: search,
                    mode: "insensitive",
                },
                description: {
                    contains: search,
                    mode: "insensitive",
                },
            },
            orderBy: {
                name: 'asc',
            },
            include: {
                networks: {
                    orderBy: {
                        name: 'asc',
                    },
                },
            },
        });
        const total = await prisma.site.count({
            where: {
                name: {
                    contains: search,
                    mode: "insensitive",
                },
                description: {
                    contains: search,
                    mode: "insensitive",
                },
            },
        });
        return NextResponse.json({ sites, total, currentPage, itemPerPage }, { status: 200 });
    } catch (error: any) {
        return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
}
