package dev.dinauer.maven.maven.core;

import dev.dinauer.maven.maven.core.model.Version;
import jakarta.ws.rs.BadRequestException;

import java.util.List;
import java.util.stream.Stream;

public class MavenUrlParser
{
    private final String path;

    private MavenUrlParser(String path)
    {
        this.path = path;
    }

    public static MavenUrlParser parse(String path)
    {
        return new MavenUrlParser(path);
    }

    public String groupId()
    {
        List<String> sections = getSections(path);
        return String.join(".", sections.subList(0, sections.size() - 3));
    }

    public String artifactId()
    {
        List<String> sections = getSections(path);
        return sections.get(sections.size() - 3);
    }

    public Version version()
    {
        List<String> sections = getSections(path);
        String raw = sections.get(sections.size() - 2);
        return new Version().setRaw(raw).setSnapshot(raw.endsWith("-SNAPSHOT"));
    }

    private static List<String> getSections(String path)
    {
        String[] sections = path.split("/");
        if (sections.length > 3)
        {
            return Stream.of(sections).filter(section -> !section.isBlank()).toList();
        }
        else
        {
            throw new BadRequestException();
        }
    }
}
