package Daje;
use Mojo::Base 'Mojolicious', -signatures;

# NAME
# ====
#
# Daje - is a Mojolicious server serving Daje stuff
#
#
#
# SYNOPSIS
# ========
#
#    use Daje;
#
# DESCRIPTION
# ===========
#
# Daje is a web server
#
#
# LICENSE
# =======
#
# Copyright (C) janeskil1525.
#
# This library is free software; you can redistribute it and/or modify
# it under the same terms as Perl itself.
#
# AUTHOR
# ======
#
# janeskil1525 E<lt>janeskil1525@gmail.comE<gt>
#
use Cwd;
use Mojo::Pg;

our $VERSION = "0.30";
# $ENV{DAJE_HOME} = '/home/jan/Project/Daje/'
#     unless $ENV{DAJE_HOME};

has home => sub {
  Mojo::Home->new(cwd);
};

has 'auth';
has 'secrets';

# This method will run once at server start
sub startup ($self) {

  # Load configuration from config file
  my $logfile = $self->home() . "/../config/config.conf";

  my $config = $self->plugin('Config',{file => $logfile});
  $self->log->path($self->home() . $self->config('log'));
  $self->log->level($self->config('loglevel'));

  $self->log->debug("Test");
  $self->helper(pg => sub {state $pg = Mojo::Pg->new->dsn(shift->config('pg'))});
  say $self->pg->db->query('select version() as version')->hash->{version};
  $self->log->debug($self->pg->db->query('select version() as version')->hash->{version});
  $self->plugin('Minion'  => { Pg => $self->pg });


  my $r = $self->routes;
  say "Daje " . $self->config->{project};
  my $auth = $r->under($self->config->{project} . '/api/' => sub ($c) {
    # say "authentichate " . $c->req->headers->header('X-Token-Check');
    # Authenticated
    say "Auth started";
    return 1 if $c->login->authenticate($c->req->headers->header('X-Token-Check'));
    # Not authenticated
    $c->render(json => '{"error":"unknown error"}');
    say "Auth failed";
    return undef;
  });

  $self->auth($auth);
  $self->plugin('Daje::Plugin::Apploader'  => { pg => $self->pg });
  # Configure the application
  $self->app->jwt->secret(@{$config->{secrets}}[0]);

  $self->secrets($config->{secrets});

}

1;


#################### pod generated by Pod::Autopod - keep this line to make pod updates possible ####################

=head1 NAME


Daje - is a Mojolicious server serving Daje stuff





=head1 SYNOPSIS


   use Daje;



=head1 DESCRIPTION


Daje is a web server




=head1 REQUIRES

L<Mojo::Pg> 

L<Cwd> 

L<Mojo::Base> 


=head1 METHODS

=head2 startup

 startup();

This method will run once at server start



=head1 AUTHOR


janeskil1525 E<lt>janeskil1525@gmail.comE<gt>



=head1 LICENSE


Copyright (C) janeskil1525.

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.



=cut

