#!/usr/bin/env perl
use strict;
use warnings;

use Mojolicious::Lite;
use LWP::UserAgent;
use MIME::Base64;
use JSON::PP;

my $CLIENT_ID = $ENV{SPOTIFY_CLIENT_ID};
my $CLIENT_SECRET = $ENV{SPOTIFY_CLIENT_SECRET};
if (!$CLIENT_ID || !$CLIENT_SECRET) {
	die "Spotify Env Vars not set\n";
}

my $AUTH_URL = "https://accounts.spotify.com/authorize"
	. "?client_id=$CLIENT_ID"
	. "&response_type=code"
	. "&redirect_uri=http://localhost:3000/auth"
	. "&scope=user-library-read%20playlist-read-private%20playlist-read-collaborative"
	. "&state=" . int(rand() * 100);

get '/' => sub {
	my $c = shift;
	$c->render(
		template => "index",
		AUTH_URL => $AUTH_URL,
	);
};

get 'auth' => sub {
	my $c = shift;

	# TODO: check state too if ever productionize / allow multiple
	# users instead of local-only
	my $code = $c->param("code");
	if (!$code) {
		$c->render(text => "Failed to Authorize; Go back and try again");
		return;
	}
	my $ua = LWP::UserAgent->new();
	my $hash = encode_base64("$CLIENT_ID:$CLIENT_SECRET", "");
	$ua->default_header('Authorization' => "Basic $hash");
	my %form = (
		grant_type => "authorization_code",
		code => $code,
		redirect_uri => "http://localhost:3000/auth",
	);
	my $res = $ua->post(
		"https://accounts.spotify.com/api/token",
		\%form,
	);
	if (!$res->is_success) {
		my $err = $res->decoded_content;
		return $c->render(text => "Error Authenticating: $err");
	}
	my $json = decode_json($res->decoded_content);
	my $tok = $json->{access_token} . "";
	$c->render(text => $tok);
};


app->start;

__DATA__

@@index.html.ep
<h1>Spotify Playlist Exporter</h1>
<p>Hello and welcome to the Spotify Playlist Exporter!</p>
<p>To start, first log in to Spotify and authorize this
app by clicking the link below:</p>
<a href=<%= $AUTH_URL %>>
Authorize
</a>
