NeahNew/app/api/announcements/[id]/route.ts
2025-05-05 13:04:01 +02:00

138 lines
4.0 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/options";
import { prisma } from "@/lib/prisma";
/**
* Check if a user exists in the database
*/
async function userExists(userId: string): Promise<boolean> {
try {
const user = await prisma.user.findUnique({
where: { id: userId },
select: { id: true }
});
return !!user;
} catch (error) {
console.error(`Error checking if user exists:`, error);
return false;
}
}
// GET - Retrieve a specific announcement
export async function GET(
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { id } = await params;
// Find announcement by ID
const announcement = await prisma.announcement.findUnique({
where: { id },
include: {
author: {
select: {
id: true,
email: true
}
}
}
});
if (!announcement) {
return NextResponse.json({ error: "Announcement not found" }, { status: 404 });
}
// Check if user has access to this announcement
const userRole = session.user.role || [];
const roles = Array.isArray(userRole) ? userRole : [userRole];
const hasAccess =
announcement.targetRoles.includes("all") ||
announcement.targetRoles.some((role: string) => roles.includes(role));
if (!hasAccess) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
return NextResponse.json(announcement);
} catch (error) {
console.error("Error fetching announcement:", error);
const errorMessage = error instanceof Error ? error.message : "Unknown error";
return NextResponse.json({
error: "Failed to fetch announcement",
details: errorMessage
}, { status: 500 });
}
}
// DELETE - Remove an announcement
export async function DELETE(
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Verify user exists in database
const userExistsInDB = await userExists(session.user.id);
if (!userExistsInDB) {
console.error("User not found in database:", session.user.id);
return NextResponse.json({
error: "User not found",
details: `The user ID from your session (${session.user.id}) doesn't exist in the database.`
}, { status: 400 });
}
// Check if user has admin, entrepreneurship, or communication role
const userRole = session.user.role || [];
const roles = Array.isArray(userRole) ? userRole : [userRole];
const hasAdminAccess = roles.some(role =>
["admin", "entrepreneurship", "communication"].includes(role)
);
if (!hasAdminAccess) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { id } = await params;
// Check if announcement exists
const announcement = await prisma.announcement.findUnique({
where: { id }
});
if (!announcement) {
return NextResponse.json({ error: "Announcement not found" }, { status: 404 });
}
// Delete the announcement
await prisma.announcement.delete({
where: { id }
});
return NextResponse.json({ message: "Announcement deleted successfully" });
} catch (error) {
console.error("Error deleting announcement:", error);
const errorMessage = error instanceof Error ? error.message : "Unknown error";
const errorCode = error.code || "UNKNOWN";
return NextResponse.json({
error: "Failed to delete announcement",
details: errorMessage,
code: errorCode
}, { status: 500 });
}
}