import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db } from "@/app/db/db";
import { user } from "@/app/db/schema/users";
import { eq } from "drizzle-orm";
import { getServerSession } from "next-auth";
import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";

const OnboardedSchema = z.object({
  onboarded: z.boolean(),
});

export async function PATCH(req: NextRequest) {
  try {
    const session = await getServerSession(AuthOptions);
    if (!session?.user?.email) {
      return new NextResponse(JSON.stringify({ msg: "Unauthenticated" }), {
        status: 401,
      });
    }

    const body = await req.json();
    const { onboarded } = OnboardedSchema.parse(body);

    const existingUser = await db.query.user.findFirst({
      where: eq(user.email, session.user.email),
    });
    if (!existingUser) {
      return new NextResponse(JSON.stringify({ msg: "User not found" }), {
        status: 404,
      });
    }

    await db
      .update(user)
      .set({ onboarded, updatedAt: new Date() })
      .where(eq(user.id, existingUser.id));

    return new NextResponse(
      JSON.stringify({ msg: "User marked as onboarded" }),
      { status: 200 }
    );
  } catch (err) {
    console.error("Error updating onboarded flag:", err);
    if (err instanceof z.ZodError) {
      return new NextResponse(
        JSON.stringify({ msg: "Invalid input", errors: err.flatten() }),
        {
          status: 400,
        }
      );
    }
    return new NextResponse(JSON.stringify({ msg: "Server error" }), {
      status: 500,
    });
  }
}
