package dev.dinauer.maven.jpa.maven;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;

import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

@Entity
@Table(name = "artifact_id")
public class ArtifactId
{
    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    private String id;

    @Column(name = "group_id_long")
    private String groupId;

    @Column(name = "artifact_id")
    private String artifactId;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "group_id")
    @JsonBackReference
    private GroupId group;

    @OneToMany(mappedBy = "artifact")
    @JsonManagedReference
    private List<Version> versions = new ArrayList<>();

    @Column(name = "updated_at")
    private ZonedDateTime updatedAt;

    @Column(name = "created_at")
    private ZonedDateTime createdAt;

    public String getId()
    {
        return id;
    }

    public ArtifactId setId(String id)
    {
        this.id = id;
        return this;
    }

    public String getGroupId()
    {
        return groupId;
    }

    public ArtifactId setGroupId(String groupId)
    {
        this.groupId = groupId;
        return this;
    }

    public String getArtifactId()
    {
        return artifactId;
    }

    public ArtifactId setArtifactId(String artifactId)
    {
        this.artifactId = artifactId;
        return this;
    }

    public GroupId getGroup()
    {
        return group;
    }

    public ArtifactId setGroup(GroupId groupId)
    {
        this.group = groupId;
        return this;
    }

    public List<Version> getVersions()
    {
        return versions.stream().sorted(Comparator.comparing(version -> new DefaultArtifactVersion(version.getVersion()))).toList().reversed();
    }

    public ArtifactId setVersions(List<Version> versions)
    {
        this.versions = versions;
        return this;
    }

    public ZonedDateTime getUpdatedAt()
    {
        return updatedAt;
    }

    public ArtifactId setUpdatedAt(ZonedDateTime updatedAt)
    {
        this.updatedAt = updatedAt;
        return this;
    }

    public ZonedDateTime getCreatedAt()
    {
        return createdAt;
    }

    public ArtifactId setCreatedAt(ZonedDateTime createdAt)
    {
        this.createdAt = createdAt;
        return this;
    }

    public int getTotalPullCount()
    {
        int i = 0;
        for (Version version : versions)
        {
            i = i + version.getPullCount();
        }
        return i;
    }
}
