import bcrypt from 'bcryptjs';
import { User } from '../../../domain/models/User.js';

export class RegisterUserCommandHandler {
  constructor(userRepository, jwtService, emailService) {
    this.userRepository = userRepository;
    this.jwtService = jwtService;
    this.emailService = emailService;
  }

  async handle(command) {
    // Validasi data
    const errors = User.validate({
      name: command.name,
      email: command.email,
      password: command.password
    });

    if (errors.length > 0) {
      throw new Error(errors.join(', '));
    }

    // Verify user does not exist
    const existingUser = await this.userRepository.findByEmail(command.email);
    if (existingUser) {
      throw new Error('User with this email already exists');
    }

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

    // Create user
    const user = await this.userRepository.create({
      name: command.name,
      email: command.email,
      password: hashedPassword
    });

    // Send welcome email
    await this.emailService.sendWelcomeEmail(user.email, user.name);

    // Generate token
    const token = this.jwtService.generateToken({
      id: user.id,
      email: user.email,
      name: user.name
    });

    return { user, token };
  }
}
