package com.social.media.application.company.handler.command;

import com.social.media.application.company.command.CreateCompanyCommand;
import com.social.media.domain.company.aggregate.Company;
import com.social.media.domain.company.repository.CompanyRepository;
import com.social.media.domain.company.valueobject.*;
import com.social.media.domain.shared.valueobject.Email;
import com.social.media.domain.shared.valueobject.Phone;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * Command Handler for CreateCompanyCommand - returns CompanyId
 */
@Component("createCompanyCommandIdHandler")
public class CreateCompanyCommandIdHandler {
    
    private final CompanyRepository companyRepository;
    
    public CreateCompanyCommandIdHandler(CompanyRepository companyRepository) {
        this.companyRepository = companyRepository;
    }
    
    @Transactional
    public CompanyId handle(CreateCompanyCommand command) {
        // Create value objects
        Email email = new Email(command.email());
        Cnpj cnpj = new Cnpj(command.cnpj());
        Phone phone = command.phoneNumber() != null ? new Phone(command.phoneNumber()) : null;
        
        Address address = null;
        if (command.street() != null || command.city() != null) {
            address = new Address(
                command.street(),
                command.number(),
                command.complement(),
                command.neighborhood(),
                command.city(),
                command.state(),
                command.postalCode(),
                command.country()
            );
        }
        
        // Validate business rules
        if (companyRepository.existsByEmail(email)) {
            throw new IllegalArgumentException("Email already exists: " + email.value());
        }
        
        if (companyRepository.existsByCnpj(cnpj)) {
            throw new IllegalArgumentException("CNPJ already exists: " + cnpj.value());
        }
        
        // Create and save company
        // Convert string plan to CompanyPlan enum
        CompanyPlan companyPlan;
        try {
            companyPlan = CompanyPlan.valueOf(command.plan().toUpperCase());
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Invalid company plan: " + command.plan(), e);
        }
        
        Company company = Company.create(
            command.companyName(),
            email,
            cnpj,
            phone,
            command.website(),
            command.activitySector(),
            companyPlan,
            address
        );
        
        Company savedCompany = companyRepository.save(company);
        return savedCompany.getId();
    }
}

