import {
  portfolio,
  portfolioUsers,
  PortfolioGoal,
  PortfolioStatus,
  PortfolioRole,
} from "@/app/db/schema/portfolio";
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/app/db/db";
import { z } from "zod";
import { serializeBigInt } from "@/app/utils";

const createPortfolioSchema = z.object({
  userId: z.string(),
  portfolioName: z.string(),
  budget: z.number().optional(),
  goal: z.enum(PortfolioGoal),
  status: z.enum(PortfolioStatus),
  role: z.enum(PortfolioRole),
});

export async function POST(request: NextRequest) {
  const body = await request.json();
  let validatedBody;

  try {
    validatedBody = createPortfolioSchema.parse(body);
  } catch (error) {
    console.error("Invalid input: ", error);
    return new NextResponse(JSON.stringify({ msg: "Invalid input" }), {
      status: 400,
    });
  }

  try {
    const { userId, portfolioName, budget, goal, status, role } = validatedBody;

    const creationDate = new Date();

    const newPortfolio = await db
      .insert(portfolio)
      .values({
        name: portfolioName,
        budget: budget,
        goal: goal,
        status: status,
        createdAt: creationDate,
        updatedAt: creationDate,
      })
      .returning({ portfolioId: portfolio.id });

    const newPortfolioId = newPortfolio[0].portfolioId;

    const response = await db
      .insert(portfolioUsers)
      .values({
        userId: BigInt(userId),
        portfolioId: newPortfolioId,
        role: role,
      })
      .returning();

    if (response.length !== 1) {
      throw new Error("Got back more than one row from insert - investigate");
    }

    return new NextResponse(JSON.stringify(response[0], serializeBigInt), {
      status: 201,
    });
  } catch (error) {
    console.error(error);
    return new NextResponse(JSON.stringify({ msg: "Insternal server error" }), {
      status: 500,
    });
  }
}
