package com.social.media.domain.shared.valueobject;

import com.social.media.domain.shared.exception.InvalidPhoneException;

import java.util.regex.Pattern;

/**
 * Value Object representing a phone number
 * Ensures phone format validation and immutability
 */
public record Phone(String value) {
    
    private static final Pattern PHONE_PATTERN = Pattern.compile(
        "^\\+?[1-9]\\d{1,14}$|^\\([0-9]{2}\\)\\s?[0-9]{4,5}-?[0-9]{4}$|^[0-9]{10,11}$"
    );
    
    public Phone {
        if (value == null || value.trim().isEmpty()) {
            throw new InvalidPhoneException("Phone cannot be null or empty");
        }
        
        String cleanedValue = value.replaceAll("[\\s\\-\\(\\)]", "");
        
        if (!PHONE_PATTERN.matcher(cleanedValue).matches()) {
            throw new InvalidPhoneException("Invalid phone format: " + value);
        }
        
        value = cleanedValue;
    }
    
    public String getFormattedValue() {
        if (value.length() == 11) {
            return String.format("(%s) %s-%s", 
                value.substring(0, 2), 
                value.substring(2, 7), 
                value.substring(7));
        } else if (value.length() == 10) {
            return String.format("(%s) %s-%s", 
                value.substring(0, 2), 
                value.substring(2, 6), 
                value.substring(6));
        }
        return value;
    }
    
    @Override
    public String toString() {
        return value;
    }
}
