
import { NextRequest, NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';
import { prisma } from '@/lib/db';
// import { UserRole } from '@prisma/client';

export const dynamic = 'force-dynamic';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { email, password, firstName, lastName, role = 'CUSTOMER', companyName } = body;

    if (!email || !password || !firstName || !lastName) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    // Check if user already exists
    const existingUser = await prisma.user.findUnique({
      where: { email },
    });

    if (existingUser) {
      return NextResponse.json(
        { error: 'User already exists with this email' },
        { status: 409 }
      );
    }

    // Validate and sanitize role
    const validRoles: any[] = ['ADMIN', 'SALES', 'CONTRACTOR', 'CUSTOMER'];
    const userRole = validRoles.includes(role) ? (role) : 'CUSTOMER';

    // Hash password
    const hashedPassword = await bcrypt.hash(password, 12);

    // Create user
    const user = await prisma.user.create({
      data: {
        email,
        password: hashedPassword,
        firstName,
        lastName,
        name: `${firstName} ${lastName}`,
        role: userRole,
        companyName,
        isActive: true,
      },
    });

    // Create role-specific profile
    if (userRole === 'CUSTOMER') {
      await prisma.customer.create({
        data: {
          userId: user.id,
        },
      });
    } else if (userRole === 'CONTRACTOR') {
      // Partner profile will be created separately through onboarding
    }

    // Log the registration
    await prisma.auditLog.create({
      data: {
        userId: user.id,
        entityType: 'user',
        entityId: user.id,
        action: 'register',
        newData: {
          email: user.email,
          role: user.role,
          name: user.name,
        },
        metadata: {
          registrationMethod: 'email',
        },
      },
    });

    // Return user without password
    const { password: _, ...userResponse } = user;
    
    return NextResponse.json({
      success: true,
      user: userResponse,
      message: 'Account created successfully',
    });

  } catch (error) {
    console.error('Signup error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
