import { db } from "@/lib/db" import { getCurrentUser } from "@/lib/session" import { revalidatePath } from "next/cache" import { NextRequest, NextResponse } from "next/server" export async function GET(req: NextRequest) { const sessionUser = await getCurrentUser() if (!sessionUser) { return NextResponse.json({ status: 401, message: 'Unauthorized' }) } let follows = undefined try { follows = await db.follows.findMany({ where: { followerId: sessionUser.id } }) } catch (error) { console.log("error", error) } return NextResponse.json({ status: 200, message: "fetched follows", follows }) } export async function PUT(req: NextRequest) { const sessionUser = await getCurrentUser() const data = await req.json() if (!sessionUser) { return NextResponse.json({ status: 401, message: 'Unauthorized' }) } try { const dbUser = await db.user.findFirst({ where: { id: sessionUser.id } }) const follow = await db.follows.findFirst({ where: { followerId: sessionUser.id, followingId: data.followingId } }) console.log("follow", follow) if (follow) { // User is already following, so unfollow console.log("delete follow") const delfollow = await db.follows.delete({ where: { followerId_followingId: { followerId: sessionUser.id, followingId: data.followingId } } }) console.log("del follow:", delfollow) } else { // User is not following, so follow console.log("create follow") await db.follows.create({ data: { followerId: sessionUser.id, followingId: data.followingId }, }) } } catch (error) { console.log("err", error) } const path = req.nextUrl.searchParams.get('path') || '/' revalidatePath(path) return NextResponse.json({ status: 200, message: 'Follow handled' }) }