import dbConnect from "../../lib/dbConnect"; import NewActivity from "../../models/NewActivities"; import { NextResponse } from "next/server"; import { setCORSHeaders, handleError } from "../../lib/apiUtils"; import { withAuth } from "../../middleware/authMiddleware"; export async function GET(request) { await dbConnect(); console.log("GET request received"); try { const isFromFrontend = request.headers.get("x-from-frontend") === "true"; let activities; let message; if (isFromFrontend) { activities = await NewActivity.find({ isActive: true }).sort({ order: 1, }); message = activities.length > 0 ? "成功获取活跃活动" : "当前没有活跃活动"; } else { // 其他请求,返回所有记录 activities = await NewActivity.find().sort({ order: 1 }); message = activities.length > 0 ? "成功获取所有活动" : "当前没有任何活动"; } const response = NextResponse.json( { success: true, data: activities, message, total: activities.length, }, { status: 200 } ); return setCORSHeaders(response); } catch (error) { console.error("Error in GET /api/new-activities:", error); return handleError(error); } } export const POST = withAuth(async (request) => { await dbConnect(); try { const { title, link, icon, order, isActive } = await request.json(); const newActivity = new NewActivity({ title, link, icon, order: order || 0, isActive: isActive !== undefined ? isActive : true, }); await newActivity.save(); const response = NextResponse.json( { success: true, message: "Activity created successfully", data: newActivity, }, { status: 201 } ); return setCORSHeaders(response); } catch (error) { console.error("Error creating activity:", error); return handleError(error); } }); export const PUT = withAuth(async (request) => { await dbConnect(); try { const { id, ...updateData } = await request.json(); console.log(id, updateData); const updatedActivity = await NewActivity.findByIdAndUpdate( id, updateData, { new: true, runValidators: true, } ); if (!updatedActivity) { return NextResponse.json( { success: false, error: "Activity not found" }, { status: 404 } ); } const response = NextResponse.json( { success: true, data: updatedActivity }, { status: 200 } ); return setCORSHeaders(response); } catch (error) { return handleError(error); } }); export const DELETE = withAuth(async (request) => { await dbConnect(); try { const url = new URL(request.url); const id = url.searchParams.get("id"); if (!id) { return NextResponse.json( { success: false, error: "Activity ID is required" }, { status: 400 } ); } const deletedActivity = await NewActivity.findByIdAndDelete(id); if (!deletedActivity) { return NextResponse.json( { success: false, error: "Activity not found" }, { status: 404 } ); } const response = NextResponse.json( { success: true, message: "Activity deleted successfully" }, { status: 200 } ); return setCORSHeaders(response); } catch (error) { return handleError(error); } }); export async function OPTIONS() { const response = new NextResponse(null, { status: 204 }); return setCORSHeaders(response); }