import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { eq, sql } 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";

const CreateFolderSchema = z.object({
  name: z.string().trim().min(1).max(120),
});

export async function POST(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 = CreateFolderSchema.safeParse(await req.json());
    if (!parsed.success) {
      return NextResponse.json({ error: "Invalid folder name" }, { status: 400 });
    }

    // New folders go last: position = current folder count.
    const [created] = await db
      .insert(userPortfolioFolders)
      .values({
        userId,
        name: parsed.data.name,
        position: sql`(select count(*) from ${userPortfolioFolders} where ${eq(
          userPortfolioFolders.userId,
          userId,
        )})`,
      })
      .returning();

    return NextResponse.json(
      {
        folder: {
          id: created.id.toString(),
          name: created.name,
          position: created.position,
        },
      },
      { status: 201 },
    );
  } catch (err) {
    console.error("Error creating folder:", err);
    return NextResponse.json({ error: "Server error" }, { status: 500 });
  }
}
