#!/usr/bin/env perl

use v5.30.0;

use strict;
use warnings;

use Data::Dumper;

use Mojo::UserAgent;
use Const::Fast;
use Path::Tiny;
use JSON;
use DateTime;

const my $config_file => "$ENV{HOME}/.config/aletareleaser.json";

if ( !-f $config_file ) {
    die "No credentials in $config_file.";
}

my $config_file_contents = path($config_file)->slurp_utf8;
my $config               = decode_json($config_file_contents);
my $username             = $config->{username} // die "No user in config.";
my $token                = $config->{token}    // die "No token in config.";
my $host                 = $config->{host}     // die "No host in config.";
my $datetime             = DateTime->now->strftime("%Y%m%d%H%M");
my $commit               = `git rev-parse HEAD`;

my $release = request(
    POST => '/repos/sergiotarxz/AletaReleaser/releases' => json => {
        body => "Aleta release from $datetime.\n"
          . "Brought to you with love by debgerme (author) & sergiotarxz (pipeline mantainer)",
        name             => "Aleta release from $datetime",
        tag_name         => "$datetime",
        target_commitish => `git rev-parse HEAD`,
    }
);

print Data::Dumper::Dumper $release;
my $release_id = $release->{id};

print Data::Dumper::Dumper request( POST =>
"/repos/sergiotarxz/AletaReleaser/releases/$release_id/assets?name=$datetime-aleta-build.tar.gz"
      => form => { attachment => { file => 'output/aleta.tar.gz' } } );

sub request {
    my $method    = shift // die "No method passed.";
    my $endpoint  = shift // die "No endpoint passed.";
    my $body_type = shift // die "No body type passed.";
    my $body      = shift // die "No body passed.";

    my $ua = Mojo::UserAgent->new();

    my $url = Mojo::URL->new("https://$host/api/v1/$endpoint");
    $url->query( token => $token );
    say $url;
    my $tx = $ua->build_tx( $method => $url => {} => $body_type => $body );
    $ua->start($tx);
    my $response = $tx->result;
    say $response->code;
    say $response->message;

    return decode_json( $response->body );
}