import { handleApiError, createResponse } from "@/src/lib/api";
import bcrypt from "bcryptjs";
import { db } from "@/src/lib/db";


export async function POST(request: Request, { params }: { params: Promise< { token: string }> }) {
  try {
    const { token } = await params;
    
    const invitation = await db.invitation.findFirst({
      where: {
        token,
        acceptedAt: null,
      },
    });

    if (!invitation) {
      return createResponse(404, 'Invalid or already used registration link');
    }

    const { email, password, username } = await request.json();
    const hashedPassword = await bcrypt.hash(password, 10);
    await db.$transaction(async (tx) => {
      const user = await tx.user.create({
        data: {
          email,
          password: hashedPassword,
          username: username.toLowerCase(),
        },
      });

      const pendingInvitations = await tx.invitation.findMany({
        where: {
          email,
          acceptedAt: null,
        },
        select: {
          portfolioId: true,
          token: true,
        },
      });


      await tx.portfolioContributor.createMany({
        data: pendingInvitations.map(invitation => ({
          portfolioId: invitation.portfolioId,
          userId: user.id,
        })),
      });

      await tx.invitation.updateMany({
        where: { email, acceptedAt: null },
        data: {
          acceptedAt: new Date(),
        },
      });
    });

    return createResponse(201, 'User created successfully');
  } catch (error) {
    return handleApiError(error);
  }
  
}
