import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { and, eq } from "drizzle-orm";
import { getServerSession } from "next-auth";
import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import { db } from "@/app/db/db";
import { userPortfolioFolders } from "@/app/db/schema/user_portfolio_config";
import { planFolderReorder } from "@/app/lib/portfolioUserConfig";

const ReorderSchema = z.object({
  orderedIds: z.array(z.string().regex(/^\d+$/)),
});

// Drag-and-drop reorder: the client sends the FULL ordered folder id list in
// one request; positions are renumbered in a single transaction so the write
// is idempotent and can't drift.
export async function PATCH(req: NextRequest) {
  try {
    const session = await getServerSession(AuthOptions);
    if (!session?.user?.dbId) {
      return NextResponse.json({ error: "Unauthenticated" }, { status: 401 });
    }
    const userId = session.user.dbId;

    const parsed = ReorderSchema.safeParse(await req.json());
    if (!parsed.success) {
      return NextResponse.json({ error: "Invalid folder order" }, { status: 400 });
    }

    const current = await db
      .select({ id: userPortfolioFolders.id })
      .from(userPortfolioFolders)
      .where(eq(userPortfolioFolders.userId, userId));

    const plan = planFolderReorder({
      currentIds: current.map((f) => f.id),
      orderedIds: parsed.data.orderedIds.map(BigInt),
    });
    if ("error" in plan) {
      return NextResponse.json({ error: plan.error }, { status: 400 });
    }

    await db.transaction(async (tx) => {
      for (const { id, position } of plan.updates) {
        await tx
          .update(userPortfolioFolders)
          .set({ position, updatedAt: new Date() })
          .where(
            and(
              eq(userPortfolioFolders.id, id),
              eq(userPortfolioFolders.userId, userId),
            ),
          );
      }
    });

    return NextResponse.json({ ok: true });
  } catch (err) {
    console.error("Error reordering folders:", err);
    return NextResponse.json({ error: "Server error" }, { status: 500 });
  }
}
