135 lines
3.7 KiB
TypeScript
135 lines
3.7 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { auth } from "@clerk/nextjs/server";
|
|
import { getDatabase } from "@/lib/database";
|
|
import log from "@/lib/logger";
|
|
import { ensureUserSynced } from "@/lib/sync-user";
|
|
|
|
export async function POST(req: Request) {
|
|
try {
|
|
const { userId: clerkUserId } = await auth();
|
|
if (!clerkUserId) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const body = await req.json();
|
|
log.debug("Approve recommendation request body", { body });
|
|
|
|
const { recommendationId, status } = body;
|
|
|
|
if (!recommendationId || !status) {
|
|
log.error("Missing required fields", {
|
|
recommendationId,
|
|
status,
|
|
receivedBody: body,
|
|
});
|
|
return NextResponse.json(
|
|
{ error: "Recommendation ID and status are required" },
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
|
|
const db = await getDatabase();
|
|
const currentUser = await ensureUserSynced(clerkUserId, db);
|
|
|
|
if (!currentUser) {
|
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
}
|
|
|
|
const canApproveRecommendations =
|
|
currentUser.role === "superAdmin" ||
|
|
currentUser.role === "admin" ||
|
|
currentUser.role === "trainer";
|
|
|
|
if (!canApproveRecommendations) {
|
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
}
|
|
|
|
const existingRecommendation = (await db.getAllRecommendations()).find(
|
|
(recommendation) => recommendation.id === recommendationId,
|
|
);
|
|
|
|
if (!existingRecommendation) {
|
|
return NextResponse.json(
|
|
{ error: "Recommendation not found" },
|
|
{ status: 404 },
|
|
);
|
|
}
|
|
|
|
if (currentUser.role !== "superAdmin") {
|
|
const targetUser = await db.getUserById(existingRecommendation.userId);
|
|
|
|
if (
|
|
!currentUser.gymId ||
|
|
!targetUser ||
|
|
targetUser.gymId !== currentUser.gymId
|
|
) {
|
|
return NextResponse.json(
|
|
{ error: "Forbidden - Cannot access users from other gyms" },
|
|
{ status: 403 },
|
|
);
|
|
}
|
|
}
|
|
|
|
// Update recommendation status
|
|
const updates: any = {
|
|
status,
|
|
approvedAt: status === "approved" ? new Date() : undefined,
|
|
approvedBy: status === "approved" ? clerkUserId : undefined,
|
|
};
|
|
|
|
// Remove undefined keys
|
|
Object.keys(updates).forEach(
|
|
(key) => updates[key] === undefined && delete updates[key],
|
|
);
|
|
|
|
const updatedRecommendation = await db.updateRecommendation(
|
|
recommendationId,
|
|
updates,
|
|
);
|
|
|
|
if (!updatedRecommendation) {
|
|
return NextResponse.json(
|
|
{ error: "Recommendation not found" },
|
|
{ status: 404 },
|
|
);
|
|
}
|
|
|
|
// If approved, create a notification for the user
|
|
if (status === "approved") {
|
|
try {
|
|
await db.createNotification({
|
|
id: crypto.randomUUID(),
|
|
userId: updatedRecommendation.userId,
|
|
title: "Recommendation Approved! 🎉",
|
|
message:
|
|
"Your AI-powered fitness recommendation has been approved by your trainer. Check it out now!",
|
|
type: "system",
|
|
read: false,
|
|
});
|
|
|
|
log.info("Notification created for approved recommendation", {
|
|
recommendationId,
|
|
userId: updatedRecommendation.userId,
|
|
});
|
|
} catch (notificationError) {
|
|
// Log error but don't fail the approval
|
|
log.error("Failed to create notification", notificationError);
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
data: updatedRecommendation,
|
|
meta: {
|
|
timestamp: new Date().toISOString(),
|
|
},
|
|
});
|
|
} catch (error) {
|
|
log.error("Error approving recommendation", error);
|
|
return NextResponse.json(
|
|
{ error: "Internal server error" },
|
|
{ status: 500 },
|
|
);
|
|
}
|
|
}
|