import { NextRequest, NextResponse } from 'next/server'; import { employeeTableFiltersSchema, newEmployeeSchema } from 'src/schemas'; import prisma from 'src/lib/prisma'; import { authenticateRequest } from 'src/lib/auth-middleware'; import { EmployeeStatus } 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') || '', status: searchParams.get('status') || '', }; // Validate filters const validatedFilters = employeeTableFiltersSchema.parse(filters); const employees = await prisma.employee.findMany({ where: { tenantId, name: { contains: validatedFilters.name, mode: 'insensitive' }, status: validatedFilters.status ? { equals: validatedFilters.status as EmployeeStatus } : undefined, }, }); return NextResponse.json(employees); } catch (error) { console.error('Error fetching employees:', 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 = newEmployeeSchema.parse(body); const employee = await prisma.employee.create({ data: { ...validatedData, tenantId, }, }); return NextResponse.json(employee, { status: 201 }); } catch (error) { console.error('Error creating employee:', error); return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); } }