package CF::Controller::Users;

use Mojo::Base 'Mojolicious::Controller';
use Mojo::Pg::PubSub;
use feature 'signatures';
no warnings qw{ experimental::signatures };

sub me ($c){
    my $user = $c->_get( $c->user->{id} ) // return;

    my $formatted = $user->formatted;

    if (
        ( $user->jitsi_allowed || $user->roles =~ /chairman|jitsi/ )
        && $c->cfg->{jitsi_base_url}
        && $c->cfg->{jitsi_room}
    ) {
        $formatted->{jitsi_url} = $c->jitsi_url(
            $c->cfg->{jitsi_room},
            $c->cfg->{jitsi_token_lifetime},
            $user->get_columns,
            moderator => ($user->roles =~ /chairman/) ? \1:\0,
            email     => $c->oauth_claims->{mail},
        );
    }

    $c->render(openapi => $c->spec_filter($formatted, 'User'));
}

sub ban ($c){
    my $user   = $c->_get( $c->stash->{id} ) // return;
    my $pubsub = Mojo::Pg::PubSub->new(pg => $c->pg);
    my $guard  = $c->schema->txn_scope_guard;

    $user->update({ banned_until => \"now()+'8 hour'", });

    #TODO: do modelu
    my $msg = $c->schema->resultset('Announcement')->from_template(
        5, $user->name,
    );

    my $announcement = $c->schema->resultset('Announcement')->create({
        user_id  => $c->user->{id},
        type     => 5,
        content  => $msg,
    });

    # potrebujeme kvuli datumu
    $announcement = $c->schema->resultset('Announcement')->find({
        id => $announcement->id,
    });

    $pubsub->json('notify')->notify( notify => {
        event   => 'announcement_created',
        payload => $announcement->format(),
    });

    $pubsub->json('notify')->notify( notify => {
        event   => 'user_banned',
        payload => $c->spec_filter($user->formatted, 'User'),
    });

    $guard->commit;
    $c->render(status => 204, text => '');
}

sub unban ($c){
    my $user   = $c->_get( $c->stash->{id} ) // return;
    my $pubsub = Mojo::Pg::PubSub->new(pg => $c->pg);
    my $guard  = $c->schema->txn_scope_guard;


    $user->update({ banned_until => undef });
    #TODO: ANN

    $pubsub->json('notify')->notify( notify => {
        event   => 'user_unbanned',
        payload => $c->spec_filter($user->formatted, 'User'),
    });

    $guard->commit;
    $c->render(status => 204, text => '');
}

sub jitsi ($c){
    $c->openapi->valid_input or return;
    my $args   = $c->req->json;
    my $user   = $c->_get( $c->stash->{id} ) // return;
    my $guard  = $c->schema->txn_scope_guard;

    $user->update({ jitsi_allowed => $args->{allowed} });

    $guard->commit;
    $c->render(status => 204, text => '');
}

sub _get ($c, $id ) {

    my $user;

    if ( $id =~ /^\d+$/) {
        $user = $c->schema->resultset('User')->find( { id => $id } );
    }
    else {
        $user = $c->schema->resultset('User')->find( { uuid => $id } );
    }

    return $c->error(404, 'User not found') if ! $user;
    return $user;
}

1;