package CF2022;
use Mojo::Base 'Mojolicious';
use Mojo::Pg;
use Mojo::Redis;
use File::Find;
use Path::Tiny qw( path );
use CF2022::Schema;

use constant SECRETS => '/run/secrets';

# This method will run once at server start
sub startup {
    my $self = shift;

    # env z docker secrets
    find(sub { $ENV{$_} = path(SECRETS . "/$_")->slurp if -f $_ }, SECRETS);

    my $cfg = $self->plugin('Config' => { file => 'cf2022.conf'} );
    $self->helper( cfg => sub { return $cfg; } );

    # Konfigurace z ENV ma prednost
    KEY:
    foreach my $key ( keys %ENV ) {
        if ( $key =~ /^CFG_(.+)/i ) {
            $cfg->{lc($1)} = $ENV{$key};
        }
    }

    # Redis
#    my $redis = Mojo::Redis->new( $cfg->{redis} );
#    $self->helper( redis => sub { return $redis; } );

    # migrace schematu
    if (! $cfg->{skip_migration}) {
        my $pg = Mojo::Pg->new
            ->dsn($cfg->{db_dsn})
            ->username($cfg->{db_username})
            ->password($cfg->{db_password})
        ;
        if ($cfg->{test}) {
            $pg->search_path(['test']);
            $pg->db->query('drop schema if exists test cascade');
            $pg->db->query('create schema test');
        }
        $pg->migrations->from_dir($self->home . '/sql');
        $pg->migrations->migrate();
        $self->helper( pg => sub { return $pg; } );
    }

    # DB Schema
    my $schema = CF2022::Schema->connect({
        dsn      => $cfg->{db_dsn},
        user     => $cfg->{db_username},
        password => $cfg->{db_password},
    });

    if ( $cfg->{test} ) {
        $schema->storage->dbh->do("set search_path to test") ;
    }

    $self->helper( schema => sub { return $schema; } );

    $self->plugin('CF2022::Helpers::Core');
    $self->plugin('CF2022::Helpers::Auth');

    $self->plugin("OpenAPI" => {
        url    => $self->home . '/openapi.yaml',
        schema => 'v3',
        plugins                        => [qw(+SpecRenderer +Cors +Security)],
        render_specification           => 1,
        render_specification_for_paths => 1,
        default_response_codes         => [400, 401, 403, 404, 429, 500, 501],
    });

    $self->defaults(
        openapi_cors_allowed_origins => ['*']
    );

    # Router
    my $r = $self->routes;
    $r->get('/')->to(cb => sub { shift->redirect_to('/api.html');});
    $r->get('/api/orders/:id/payment.png')->to('Orders#qr');

}

1;