package LasTres::Controller::Websocket::InputPacket::ExecuteAction;

use v5.36.0;
use strict;
use warnings;
use utf8;

use Moo;
use List::AllUtils;

sub identifier {
    return 'execute_action';
}

sub handle ( $self, $ws, $session, $data ) {
    if ( ref $data ne 'HASH' ) {
        return $ws->send( to_json( { error => "Data should be a hashref." } ) );
    }
    if ( !defined $session->{pj} ) {
        return $ws->send(
            to_json( { error => 'The pj for this session does not exist.' } ) );
    }
    $session->{pj} = $session->{pj}->get_from_storage;
    my $pj        = $session->{pj};
    my $action_id = $data->{action};
    if ( !defined $action_id ) {
        return $ws->send( to_json( { error => 'No action set.' } ) );
    }
    my @actions = $pj->actions->@*;
    my ($action) = List::AllUtils::onlyres { $_->identifier eq $action_id && $_ } @actions;
    if (!defined $action) {
        return $ws->send( to_json( { error => "Could not find action $action_id." } ) );
    }
    if ( $action->is_disabled($pj) ) {
        return $ws->send( to_json( { error => "@{[$action->identifier]} is disabled." } ) );
    }
    $action->callback($pj);
    my $team = $pj->team;
    for my $member ( $team->combat_members->@* ) {
        $member->update_team_sprites;
        $member->update_location;
        $member->update_actions;
    }
}
1;
