package click.kamil.springstatemachineexporter.analysis.flow.alloc;

import org.eclipse.jdt.core.dom.ClassInstanceCreation;

import java.util.Objects;

/**
 * A concrete {@code new T(...)} allocation site relevant to receiver-type narrowing.
 * Optional CIC AST is retained for getter peels (ctor args) but is not part of equality —
 * uniqueness remains by type FQN.
 */
public final class AllocationSite {

    private final String typeFqn;
    private final ClassInstanceCreation cic;

    public AllocationSite(String typeFqn) {
        this(typeFqn, null);
    }

    public AllocationSite(String typeFqn, ClassInstanceCreation cic) {
        this.typeFqn = typeFqn;
        this.cic = cic;
    }

    public String typeFqn() {
        return typeFqn;
    }

    /**
     * Source CIC when known (for nested ctor-arg peels). May be null for text-only sites.
     */
    public ClassInstanceCreation cic() {
        return cic;
    }

    /**
     * Prefer the site that retains CIC AST when merging equal type FQNs.
     */
    public AllocationSite preferRich(AllocationSite other) {
        if (other == null) {
            return this;
        }
        if (!Objects.equals(typeFqn, other.typeFqn)) {
            return this;
        }
        if (this.cic == null && other.cic != null) {
            return other;
        }
        return this;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof AllocationSite that)) {
            return false;
        }
        return Objects.equals(typeFqn, that.typeFqn);
    }

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

    @Override
    public String toString() {
        return "AllocationSite{" + typeFqn + (cic != null ? "+cic" : "") + '}';
    }
}
