53 lines
1.4 KiB
TypeScript
53 lines
1.4 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { auth } from "@clerk/nextjs/server";
|
|
import { ensureUserSynced } from "@/lib/sync-user";
|
|
import { getDatabase } from "@/lib/database";
|
|
import { isChatError, listThreadsForUser } from "@/lib/chat";
|
|
import log from "@/lib/logger";
|
|
|
|
interface Params {
|
|
params: Promise<{ id: string }>;
|
|
}
|
|
|
|
export async function GET(_request: Request, { params }: Params) {
|
|
try {
|
|
const { userId } = await auth();
|
|
if (!userId) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const { id: threadId } = await params;
|
|
const db = await getDatabase();
|
|
const currentUser = await ensureUserSynced(userId, db);
|
|
if (!currentUser) {
|
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
}
|
|
|
|
const threads = await listThreadsForUser({
|
|
id: currentUser.id,
|
|
role: currentUser.role,
|
|
gymId: currentUser.gymId,
|
|
});
|
|
|
|
const thread = threads.find((item) => item.id === threadId);
|
|
if (!thread) {
|
|
return NextResponse.json({ error: "Thread not found" }, { status: 404 });
|
|
}
|
|
|
|
return NextResponse.json({ thread });
|
|
} catch (error) {
|
|
if (isChatError(error)) {
|
|
return NextResponse.json(
|
|
{ error: error.message },
|
|
{ status: error.status },
|
|
);
|
|
}
|
|
|
|
log.error("Failed to fetch chat thread", error);
|
|
return NextResponse.json(
|
|
{ error: "Internal server error" },
|
|
{ status: 500 },
|
|
);
|
|
}
|
|
}
|