import getServerCredential from "@/common/libs/getServerCredential";
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "prisma/client";

export async function GET(request: NextRequest) {
  const PAGE_SIZE = 30;

  const searchParams = request.nextUrl.searchParams;
  const search = searchParams.get('search');
  const page = searchParams.get('page');
  const intPage: number = page ? parseInt(page) : 1;
  const paramCompanyId = searchParams.get('companyId')
  const companyId = paramCompanyId ? parseInt(paramCompanyId) : null

  const credential = getServerCredential()

  if (!credential) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const products = await prisma.product.findMany({
    where: {
      AND: {
        OR: [
          { name: { mode: 'insensitive', contains: search ?? '' } },
          { barcode: { mode: 'insensitive', contains: search ?? '' } },
          { itemCode: { mode: 'insensitive', contains: search ?? '' } },
        ],
        companyId: companyId ?? credential.companyId
      }
    },
    include: { company: true },
    take: PAGE_SIZE,
    skip: (intPage - 1) * PAGE_SIZE
  })

  const count = await prisma.product.count({
    where: {
      AND: {
        OR: [
          { name: { mode: 'insensitive', contains: search ?? '' } },
          { barcode: { mode: 'insensitive', contains: search ?? '' } },
          { itemCode: { mode: 'insensitive', contains: search ?? '' } },
        ],
        companyId: companyId ?? credential.companyId
      }
    }
  })
  const pagination = {
    page: intPage,
    totalPage: Math.ceil(count / PAGE_SIZE),
  }

  return NextResponse.json({ products, ...pagination })
}

// TODO: Search case sensitive
// TODO: Submit harus di done 