import { NextRequest, NextResponse } from 'next/server'; import prisma from 'src/lib/prisma'; import { tenantSchema } from 'src/schemas'; import { z } from 'zod'; import { authenticateRequest } from 'src/lib/auth-middleware'; export async function GET(request: NextRequest) { try { const auth = await authenticateRequest(request); if (auth instanceof NextResponse) { return auth; // Return error response if authentication failed } const { tenantId } = auth; const tenant = await prisma.tenant.findUnique({ where: { id: tenantId }, }); if (!tenant) { return NextResponse.json({ error: 'No tenant found' }, { status: 404 }); } return NextResponse.json(tenant); } catch (error) { console.error('Error fetching tenant:', error); return NextResponse.json({ error: 'Failed to fetch tenant' }, { status: 500 }); } } export async function POST(request: NextRequest) { try { const auth = await authenticateRequest(request); if (auth instanceof NextResponse) { return auth; } const { tenantId } = auth; const body = await request.json(); // Validate request body const validatedData = tenantSchema.parse(body); // Check if tenant already exists const existingTenant = await prisma.tenant.findUnique({ where: { id: tenantId, }, }); if (existingTenant) { return NextResponse.json({ error: 'Tenant already exists' }, { status: 400 }); } // Create new tenant with the authenticated tenantId const tenant = await prisma.tenant.create({ data: { ...validatedData, id: tenantId, // Ensure the tenant is created with the authenticated tenantId }, }); return NextResponse.json(tenant, { status: 201 }); } catch (error) { if (error instanceof z.ZodError) { return NextResponse.json( { error: 'Invalid request data', details: error.errors }, { status: 400 } ); } console.error('Error creating tenant:', error); return NextResponse.json({ error: 'Failed to create tenant' }, { status: 500 }); } }