package com.pablotj.ai.chat.domain.model;

import java.util.Objects;

/**
 * Value Object representing message content with validation and formatting.
 */
public final class MessageContent {

    private static final int MAX_LENGTH = 10000;
    private static final int MIN_LENGTH = 1;

    private final String text;

    private MessageContent(String text) {
        this.text = validateAndNormalize(text);
    }

    public static MessageContent of(String text) {
        return new MessageContent(text);
    }

    private String validateAndNormalize(String text) {
        if (text == null) {
            throw new IllegalArgumentException("Message content cannot be null");
        }

        String normalized = text.trim();

        if (normalized.length() < MIN_LENGTH) {
            throw new IllegalArgumentException("Message content cannot be empty");
        }

        if (normalized.length() > MAX_LENGTH) {
            throw new IllegalArgumentException(
                    String.format("Message content cannot exceed %d characters", MAX_LENGTH)
            );
        }

        return normalized;
    }

    public String getText() {
        return text;
    }

    public int getLength() {
        return text.length();
    }

    public boolean isEmpty() {
        return text.isEmpty();
    }

    public MessageContent truncate(int maxLength) {
        if (text.length() <= maxLength) {
            return this;
        }
        return new MessageContent(text.substring(0, maxLength) + "...");
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        MessageContent that = (MessageContent) obj;
        return Objects.equals(text, that.text);
    }

    @Override
    public int hashCode() {
        return Objects.hash(text);
    }

    @Override
    public String toString() {
        return text;
    }
}
