import { db } from "@/lib/db";
import { getCurrentUser } from "@/lib/session";
import { revalidatePath } from "next/cache";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
	const user = await getCurrentUser();

	if (!user) {
		return NextResponse.json({ status: 401, message: 'Unauthorized' });
	}

	const userId = user.id;
	const content = await req.json()

	try {
		await db.post.create({
			data: {
				content: content.gweet,
				userId: userId,
			}
		})
		const path = req.nextUrl.searchParams.get('path') || '/';
		revalidatePath(path);

		return NextResponse.json({ status: 201, message: 'Message Created' })

	} catch (error: any) {
		return NextResponse.json({ status: 500, message: error.message })
	}
}

export async function GET() {
	try {
		const messages = await db.post.findMany({
			orderBy: {
				createdAt: "desc"
			},
			include: {
				user: true,
				Comment: true,
				Like: true
			},
		})

		return NextResponse.json(messages);
	} catch (error) {
		return NextResponse.json(error, { status: 500 });
	}
}