#!/usr/bin/perl

use v5.36;
use open qw(:std :utf8);

use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;

@ARGV = qw( briandfoy/business-isbn-data );

my( $user, $repo ) = split m|/|, $ARGV[0];

my $url = sprintf 'https://api.github.com/repos/%s/%s/pulls',
	$user,
	$repo;

my $headers = {
	Accept                 => 'application/vnd.github+json',
	Authorization          => $ENV{GITHUB_TOKEN},
	'X-GitHub-Api-Version' => '2022-11-28',
	};

my $tx = $ua->get(
	$url =>
	$headers
	);

my $data = $tx->res->json;

my $feed = start_xml();

my $entry_count = 0;
foreach my $pr ( $data->@* ) {
	next unless $pr->{'state'} eq 'open';
	$entry_count++;

	my $entry = tag('entry')->at('entry');
	$entry->append_content( tag( id      => $pr->{id}      ) );
	$entry->append_content( tag( title   => $pr->{title}         ) );

	$entry->append_content( tag( 'link' ) );
	$entry->at('link')->attr( rel => 'alternate', href => $pr->{html_url} );

	$feed->append_content($entry);
	}

add_default_item($feed) unless $entry_count;

say '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' . $feed->to_pretty_string;


sub add_default_item ( $feed ) {
	my $message = "No Business::ISBN::Data pull requests for " . localtime;
	my $entry = tag('entry')->at('entry');
	$entry->append_content( tag( id      => "$$-" . time ) );
	$entry->append_content( tag( title   => $message ) );
	$entry->append_content( tag( content => $message ) );
	$feed->append_content($entry);
	}

sub now { # 2003-12-13T18:30:02Z
	my @gmtime = gmtime();
	$gmtime[5] += 1900;
	$gmtime[4] += 1;

	my $now = sprintf '%4d-%02d-%02dT%02d:%02d:%02dZ', @gmtime[5,4,3,2,1,0];
	}

sub start_xml () {
	state $rc = require Mojo::DOM;
	my $feed = Mojo::DOM
		->with_roles('+PrettyPrinter')
		->new_tag('feed', xmlns => 'http://www.w3.org/2005/Atom');

	my $description = <<~"HERE";
			Pull requests to Business::ISBN::Data
			HERE

	my %hash = (
		id          => 'https://www.theperlreview.com/business-isbn-data.xml',
		title       => 'Business::ISBN::Data',
		subtitle    => $description,
		updated     => now(),
		);

	foreach my $tag ( keys %hash ) {
		$feed->at('feed')->append_content( tag($tag, $hash{$tag}) );
		}

	$feed->at('feed')->append_content(
		Mojo::DOM->new_tag( 'link', rel => 'self', href => $hash{id}, '' )
		);

	$feed->at('feed');
	}

sub tag ( $tag, $content = undef ) { Mojo::DOM->new_tag($tag, $content // '' ) }
