package LasTres::Schema::Result::Team;

use v5.36.0;

use strict;
use warnings;

use parent 'DBIx::Class::Core';

use LasTres::Location;

__PACKAGE__->table('teams');

__PACKAGE__->add_columns(
    uuid => {
        data_type => 'uuid',
        is_nullable => 0,
    },
    leader => {
        data_type => 'uuid',
        is_nullable => 1,
        is_foreign_key => 1,
    },
    name => {
        data_type => 'text',
        is_nullable => 0,
    },
    planet => {
        data_type => 'text',
        is_nullable => 0,
        accessor => '_planet',
    },
    super_area => {
        data_type => 'text',
        is_nullable => 0,
        accessor => '_super_area',
    },
    area => {
        data_type => 'text',
        is_nullable => 0,
        accessor => '_area',
    },
    location => {
        data_type => 'text',
        is_nullable => 0,
        accessor => '_location',
    },
);

# May throw error, it is needed to handle.
sub location {
    my $self = shift;
    my $location = shift;
    my $planet;
    my $super_area;
    my $area;
    if (defined $location) {
        $self->_location($location->identifier);
        $area = $location->parent;
        $self->_area($area->identifier);
        $super_area = $area->parent;
        $self->_super_area($super_area->identifier);
        $planet = $super_area->parent;
        $self->_planet($planet->identifier);
    }
    $location = $self->_location;
    $area = $self->_area;
    $super_area = $self->_super_area;
    $planet = $self->_planet;
    $location = LasTres::Location::get($planet, $super_area, $area, $location);
    return $location;
}
__PACKAGE__->set_primary_key('uuid');
__PACKAGE__->add_unique_constraint(u_name => ['name']);
__PACKAGE__->has_many('members', 'LasTres::Schema::Result::PJ', 'team');
__PACKAGE__->belongs_to('leader', 'LasTres::Schema::Result::PJ');
1;
