import { NextRequest, NextResponse } from "next/server"; import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { prisma } from "@/lib/prisma"; // GET - Retrieve all announcements (with role filtering) export async function GET(req: NextRequest) { try { const session = await getServerSession(authOptions); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } // Get user role from session const userRole = session.user.role || []; const roles = Array.isArray(userRole) ? userRole : [userRole]; // Query announcements based on role const announcements = await prisma.announcement.findMany({ where: { OR: [ { targetRoles: { has: "all" } }, { targetRoles: { hasSome: roles } } ] }, orderBy: { createdAt: "desc" }, include: { author: { select: { id: true, email: true } } } }); return NextResponse.json(announcements); } catch (error) { console.error("Error fetching announcements:", error); return NextResponse.json({ error: "Failed to fetch announcements" }, { status: 500 }); } } // POST - Create a new announcement export async function POST(req: NextRequest) { try { const session = await getServerSession(authOptions); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } // 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 }); } // Parse request body const { title, content, targetRoles } = await req.json(); // Validate request body if (!title || !content || !targetRoles || !targetRoles.length) { return NextResponse.json({ error: "Missing required fields" }, { status: 400 }); } // Create new announcement const announcement = await prisma.announcement.create({ data: { title, content, targetRoles, authorId: session.user.id } }); return NextResponse.json(announcement, { status: 201 }); } catch (error) { console.error("Error creating announcement:", error); return NextResponse.json({ error: "Failed to create announcement" }, { status: 500 }); } }