import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import bcrypt from 'bcryptjs';
import { prisma } from '@/lib/prisma';

const signupSchema = z.object({
  email: z.string().email('Invalid email address'),
  password: z.string().min(8, 'Password must be at least 8 characters'),
  firstName: z.string().min(2, 'First name must be at least 2 characters'),
  lastName: z.string().min(2, 'Last name must be at least 2 characters'),
  phoneNumber: z.string().optional(),
  zipCode: z.string().optional(),
  city: z.string().optional(),
  country: z.string().min(1, 'Please select a country'),
  role: z.enum(['CLIENT', 'FREELANCER']),
});

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // Validate input
    const validatedData = signupSchema.parse(body);
    
    // Check if user already exists
    const existingUser = await prisma.user.findUnique({
      where: { email: validatedData.email }
    });
    
    if (existingUser) {
      return NextResponse.json(
        { message: 'User with this email already exists' },
        { status: 400 }
      );
    }
    
    // Hash password
    const hashedPassword = await bcrypt.hash(validatedData.password, 12);
    
    // Validate the selected country exists
    const selectedCountry = await prisma.country.findUnique({
      where: { id: validatedData.country }
    });
    
    if (!selectedCountry) {
      return NextResponse.json(
        { message: 'Invalid country selected' },
        { status: 400 }
      );
    }
    
    // Create user with transaction to ensure data consistency
    const user = await prisma.$transaction(async (tx: any) => {
      const newUser = await tx.user.create({
        data: {
          email: validatedData.email,
          password: hashedPassword,
          role: validatedData.role,
          provider: 'email',
        }
      });
      
             const profile = await tx.profile.create({
         data: {
           userId: newUser.id,
           firstName: validatedData.firstName,
           lastName: validatedData.lastName,
           phone: validatedData.phoneNumber,
           address: validatedData.city ? `${validatedData.city}${validatedData.zipCode ? ', ' + validatedData.zipCode : ''}` : validatedData.zipCode,
           countryId: selectedCountry.id,
           city: validatedData.city ?? '',
           zipCode:validatedData.zipCode ??''
         }
       });
      
      return { ...newUser, profile };
    });
    
    // Remove password from response
    const { password, ...userWithoutPassword } = user;
    
    return NextResponse.json(
      { 
        message: 'User created successfully',
        user: userWithoutPassword
      },
      { status: 201 }
    );
    
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { message: 'Validation error', errors: error.issues },
        { status: 400 }
      );
    }
    
    console.error('Signup error:', error);
    return NextResponse.json(
      { message: 'Internal server error', details: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    );
  }
} 