package DhMakeRaku::GitLab;

# ABSTRACT: Manage Debian package files of Raku modules

use strict;
use warnings;
use autodie qw(:all);

use Exporter qw/import/;

use Path::Tiny;
use Pod::POM;
use v5.32;
use GitLab::API::v4::Constants 0.11 qw( :all );
# https://metacpan.org/pod/GitLab::API::v4
use GitLab::API::v4 0.13;

use feature qw/signatures/;
no warnings qw/experimental::signatures/;

our @EXPORT_OK = qw/setup_project/;

sub setup_api_client ($config) {
    die "Cannot find gitlab token (not in ~/.git-credentials and missing DRT_SALSA_PRIVATE_TOKEN)\n"
        unless $config->{private_token};
    return GitLab::API::v4->new(
        url           => "https://".$config->{api_host}.$config->{api_path},
        private_token => $config->{private_token},
    );
}

sub get_project ($config, $client, $name) {
    my $found = $client->projects({
        search         => $name,
        simple => 1,
    });
    my $proj_data;;
    foreach my $proj ($found->@*) {
        if (grep {$proj->{namespace}{id} == $config->{$_}} qw/team_id team_modules_id/) {
            die "error: found more than one project" if $proj_data;
            $proj_data = $proj;
        }
    }
    return $proj_data;
}

# don't know how to test this one automatically
sub create_module_project ($config, $client, $name) {
    # https://docs.gitlab.com/ee/api/projects.html#create-project
    return $client->create_project({
        name                => $name,
        visibility          => 'public',
        wiki_access_level   => 'disabled',
        issues_access_level => 'disabled',
        default_branch      => 'debian/sid',
        description         => "Debian package for Raku module $name",
        namespace_id        => $config->{team_modules_id},
    });
}

# project data (see https://docs.gitlab.com/ee/api/projects.html)
# - id (numeric)
# - ssh_url_to_repo: "git@example.com:diaspora/diaspora-client.git",
# - http_url_to_repo: "http://example.com/diaspora/diaspora-client.git",

sub setup_project ($config, $name) {
    my $client = setup_api_client($config);
    my $proj_data = get_project($config, $client, $name);

    if (not $proj_data) {
        say "Creating project $name on salsa...";
        $proj_data = create_module_project($config, $client, $name);
    }

    return $proj_data->{http_url_to_repo};
}

1;
