import { NextRequest, NextResponse } from "next/server";
import { prisma } from "prisma/client";
import { Credential } from "@/common/types/auth"

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const search = searchParams.get('search');

  const credentialStr = request.cookies.get('credential')?.value
  const credential: Credential | null = credentialStr ? JSON.parse(credentialStr) : null

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

  const { companyId } = credential

  const locations = await prisma.location.findMany({
    where: {
      companyId,
      name: { contains: search ?? '' }
    },
    take: 20
  })

  return NextResponse.json(locations)
}