import bcrypt from 'bcryptjs';
import { db } from '@/lib/db';
import { NextRequest } from 'next/server';
import { createResponse, handleApiError } from '@/src/lib/api';
import { validateInviteToken } from '@/src/utils/invite';

export async function POST(request: NextRequest) {
  try {
    const { email, password, username, invite } = 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(),
        },
      });

      if (invite) {
        const portfolioId = validateInviteToken(invite);
        if (!portfolioId) {
          throw new Error('Invalid or tampered invitation token');
        }

        await tx.portfolioContributor.create({
          data: {
            userId: user.id,
            portfolioId,
          },
        });
      }

      return user;
    });

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