import { NextRequest, NextResponse } from 'next/server'; import { customerTableFiltersSchema, newCustomerSchema } from 'src/schemas'; import prisma from 'src/lib/prisma'; import { authenticateRequest } from 'src/lib/auth-middleware'; import { Prisma, ClientStatus } from '@prisma/client'; export async function GET(request: NextRequest) { try { // Authenticate the request const authResult = await authenticateRequest(request); if (authResult instanceof NextResponse) { return authResult; } const { userId, tenantId } = authResult; const searchParams = request.nextUrl.searchParams; const filters = { name: searchParams.get('name') || '', role: searchParams.getAll('role'), status: searchParams.get('status') || '', }; // Validate filters const validatedFilters = customerTableFiltersSchema.parse(filters); // const customers = await prisma.$queryRaw` // SELECT * FROM "Client" // WHERE "tenant_id" = ${tenantId} // AND LOWER(name) LIKE LOWER(${`%${validatedFilters.name}%`}) // ${ // validatedFilters.status // ? Prisma.sql`AND status = ${validatedFilters.status}::"CustomerStatus"` // : Prisma.sql`AND TRUE` // } // `; const customers = await prisma.client.findMany({ where: { tenantId, name: { contains: validatedFilters.name, mode: 'insensitive', }, ...(validatedFilters.status && { status: validatedFilters.status as ClientStatus, }), }, }); return NextResponse.json(customers); } catch (error) { console.error('Error fetching customers:', error); return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); } } export async function POST(request: NextRequest) { try { // Authenticate the request const authResult = await authenticateRequest(request); if (authResult instanceof NextResponse) { return authResult; } const { userId, tenantId } = authResult; const body = await request.json(); const validatedData = newCustomerSchema.parse(body); console.log('validatedData', validatedData); const customer = await prisma.client.create({ data: { ...validatedData, tenantId, }, }); return NextResponse.json(customer, { status: 201 }); } catch (error) { console.error('Error creating customer:', error); return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); } }