import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@repo/db";

export async function GET(req: NextRequest): Promise<NextResponse> {
	try {
		const { searchParams } = new URL(req.url);
		const id = searchParams.get("id");

		if (!id) {
			return NextResponse.json({ error: "User id is required" }, { status: 400 });
		}

		const user = await prisma.user.findUnique({
			where: { id: id },
		});

		if (!user) {
			return NextResponse.json({ error: "User not found" }, { status: 404 });
		}

		return NextResponse.json(user, { status: 200 });
	} catch (error) {
		console.error(error);
		return NextResponse.json({ error: "Failed to fetch user" }, { status: 500 });
	}
}

export async function POST(req: NextRequest): Promise<NextResponse> {
	try {
		const { searchParams } = new URL(req.url);
		const id = searchParams.get("id");

		if (!id) {
			return NextResponse.json({ error: "User id is required" }, { status: 400 });
		}

		const body = await req.json();

		const updatedUser = await prisma.user.update({
			where: { id: id },
			data: body,
		});

		return NextResponse.json(updatedUser, { status: 200 });
	} catch (error) {
		console.error(error);
		return NextResponse.json({ error: "Failed to update user" }, { status: 500 });
	}
}
