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 { CustomerStatus } from '@prisma/client'; import { Prisma } 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); // Replace Prisma query with raw SQL const customers = await prisma.$queryRaw` SELECT * FROM "Client" WHERE "tenantId" = ${tenantId} AND LOWER(name) LIKE LOWER(${`%${validatedFilters.name}%`}) ${ validatedFilters.status ? Prisma.sql`AND status = ${validatedFilters.status}::"CustomerStatus"` : Prisma.sql`AND TRUE` } `; 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, // userId, tenantId, }, }); return NextResponse.json(customer, { status: 201 }); } catch (error) { console.error('Error creating customer:', error); return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); } }