use v5.26;
use warnings;
use utf8;

package App::LazyShoppingList::API;
use Dancer2;
use Exporter qw(import);

our $VERSION = '0.1';

our @EXPORT = qw( &get_database &get_lists_version &increment_lists_version
    &invalid_input exception );

use Dancer2::Plugin::DBIC;

use experimental 'signatures';

my %fixed_db_settings = (
    RaiseError => 1,
    AutoCommit => 1,
    PrintError => 0,
);
#my @on_db_connect_do = (
#    "SET NAMES 'utf8'",
#);
#
#hook database_connected => sub {
#    my $dbh = shift;
#
#    $dbh->do($_) for @on_db_connect_do;
#};

sub get_database {
    $ENV{DBIC_TRACE}=1;
    my %cfg = %{ config->{db} };
    DBICx::Sugar::config( { default => \%cfg } );
    $cfg{schema_class} = 'App::LazyShoppingList::Schema';
    while(my($k,$v) = each %fixed_db_settings ) {
        $cfg{options}{$k} = $v;
    }
    my $dbh = DBICx::Sugar::schema();

    warn to_json(DBICx::Sugar::get_config());

    $dbh->connect;

    return $dbh;
}

sub get_lists_version($dbh) {
    my $g = $dbh->resultset('Globals')->single;
    return  $g->lists_version;
}

sub increment_lists_version($dbh) {
    $dbh->storage->dbh_do(
        sub {
            my ( $storage, $dbh ) = @_;
            $dbh->do(
                'UPDATE globals SET lists_version = lists_version + 1');
        }
    );

    my $g = $dbh->resultset('Globals')->single;
    return $g->lists_version;
}

sub exception($http_code, $text) {
    status $http_code;
    return { exception => $text };
}

sub invalid_input($details = undef) {
    return exception 400,
        "Invalid input" . ( defined($details) ? " ($details)" : '' );
}


1;
