package LasTres::Controller::Websocket::InputPacket::MoveBetweenLocations;

use v5.36.0;

use strict;
use warnings;

use feature 'signatures';

use Data::Dumper;

use Moo;

use JSON;
use JSON qw/to_json/;

use LasTres::Flags;
use LasTres::Redis;
use LasTres::DAO::PJs;
use LasTres::Location;

with 'LasTres::Controller::Websocket::InputPacket';

my $redis          = LasTres::Redis->new;
my $result_set_pjs = LasTres::DAO::PJs->ResultSet;

sub identifier {
    return 'move_to';
}

sub handle ( $self, $ws, $session, $data ) {
    if ( ref $data ne 'HASH' ) {
        return $ws->send( to_json( { error => "Data should be a hashref." } ) );
    }
    my $planet      = $data->{planet};
    my $super_area  = $data->{super_area};
    my $area        = $data->{area};
    my $location_id = $data->{location};
    if (   !defined $planet
        || !defined $super_area
        || !defined $area
        || !defined $location_id )
    {
        return $ws->send( to_json( { error => "The location is malformed" } ) );
    }
    $session->{pj} = $session->{pj}->get_from_storage;
    if ( !defined $session->{pj} ) {
        return $ws->send(
            to_json(
                { error => 'You have not set a pj yet for this websocket.' }
            )
        );
    }
    my $pj = $session->{pj};
    my $team   = $pj->team;
    my $leader = $team->leader;
    if ( $leader->uuid ne $pj->uuid ) {
        return $ws->send(
            to_json( { error => 'You are not the team leader.' } ) );
    }
    my $location = $team->location;
    my $wanted_location =
      LasTres::Location::get( $planet, $super_area, $area, $location_id );
    if ( !$location->is_connected_by_move( $wanted_location, $pj ) ) {
        return $ws->send( to_json( { error => 'You cannot travel there.' } ) );
    }

    $wanted_location->move($team);
}
1;
