use utf8;

package JSON::API::v1::Resource;
our $VERSION = '0.002';
use Moose;
use namespace::autoclean;
use Carp qw(croak);

# ABSTRACT: A JSON API Resource object

has id => (
    is        => 'ro',
    isa       => 'Str',
    predicate => 'has_id',
);

has type => (
    is        => 'ro',
    isa       => 'Str',
    predicate => 'has_type',
);

has attributes => (
    is        => 'ro',
    isa       => 'HashRef',
    predicate => 'has_attributes',
);

has relationships => (
    is        => 'ro',
    isa       => 'Defined',
    predicate => 'has_relationships',
);


sub TO_JSON {
    my $self = shift;

    if ($self->has_id && $self->has_type) {
        return {
            id   => $self->id,
            type => $self->type,
            $self->has_attributes ? (attributes => $self->attributes) : (),
            $self->has_meta_object ? (meta => $self->meta_object) : (),
        };
    }
    elsif ($self->has_id || $self->has_type) {
        croak(
            sprintf("Unable to represent a valid data object, %s is missing",
                $self->has_id ? 'type' : 'id')
        );
    }
    else {
        return undef;
    }
}

with qw(
    JSON::API::v1::Roles::TO_JSON
    JSON::API::v1::Roles::MetaObject
);

__PACKAGE__->meta->make_immutable;

__END__

=pod

=encoding UTF-8

=head1 NAME

JSON::API::v1::Resource - A JSON API Resource object

=head1 VERSION

version 0.002

=head1 SYNOPSIS

    use JSON::API::v1::Resource;
    my $object = JSON::API::v1::Resource->new(
        # If omitted, this becomes a "NULL" object
        id   => 1,
        type => 'example',

        # optional
        attributes => {
            'title' => 'Some example you are',
        },
    );

    $object->TO_JSON_API_V1;

=head1 DESCRIPTION

This module attempts to make a Moose object behave like a JSON API object as
defined by L<jsonapi.org>. This object adheres to the v1 specification.

=head1 ATTRIBUTES

=head1 METHODS

=head1 SEE ALSO

=over

=item * L<https://jsonapi.org/format/#document-resource-objects>

=back

=head1 AUTHOR

Wesley Schwengle <waterkip@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2020 by Wesley Schwengle.

This is free software, licensed under:

  The (three-clause) BSD License

=cut
