import { db } from "@/app/db/db";
import { NextRequest, NextResponse } from "next/server";
import { portfolioUsers } from "@/app/db/schema/portfolio";
import { and, eq } from "drizzle-orm";
import { z } from "zod";

const PermissionsBodySchema = z.object({
  userId: z.string(),
  action: z.enum(["delete", "update"]),
});

export async function POST(request: NextRequest, props: { params: Promise<{ portfolioId: string }> }) {
  const params = await props.params;
  // This endpoint lives at portfolio/{portfolioId}/permissions and will return the permissions level for a given portfolio
  // Call this endpoint with a) userId, b) portfolioId, c) an action and this api will tell you if that person can do that thing

  const body = await request.json();
  let validatedBody;

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

  const action = validatedBody.action;
  const userId = validatedBody.userId;
  const portfolioId = params.portfolioId;

  const existingPortfolioPermissions = await db.query.portfolioUsers.findFirst({
    where: and(
      eq(portfolioUsers.portfolioId, BigInt(portfolioId)),
      eq(portfolioUsers.userId, BigInt(userId))
    ),
  });

  if (!existingPortfolioPermissions) {
    return new NextResponse(
      JSON.stringify({ error: "Portfolio not found or unauthorized" }),
      { status: 404 }
    );
  }

  const role = existingPortfolioPermissions.role;

  let permitted;

  // If the action is a delete, we only allow an admin or creator to delete
  if (action === "delete") {
    if (role === "admin" || role === "creator") {
      permitted = true;
    } else {
      permitted = false;
    }
  }

  // If the action is an update, we allow an individual admin, creator or write role to update
  if (action === "update") {
    if (role === "admin" || role === "creator" || role === "write") {
      permitted = true;
    } else {
      permitted = false;
    }
  }

  // Returning a successful response
  return new NextResponse(
    JSON.stringify({
      permitted: permitted,
    }),
    {
      status: 200,
    }
  );
}
