package Sietima::Message;
use Moo;
use Sietima::Policy;
use Types::Standard qw(ArrayRef Object);
use Sietima::Types qw(Address AddressFromStr
                      Subscriber SubscriberFromAddress SubscriberFromStr
                      EmailMIME);
use Email::Address;
use Sietima::Subscriber;
use Email::MIME;
use namespace::clean;

our $VERSION = '1.1.5'; # VERSION
# ABSTRACT: an email message with an envelope


has mail => (
    is => 'ro',
    isa => EmailMIME,
    required => 1,
);


has from => (
    is => 'ro',
    isa => Address,
    coerce => AddressFromStr,
    required => 1,
);


my $subscriber_array = ArrayRef[
    Subscriber->plus_coercions(
        SubscriberFromStr,
        SubscriberFromAddress,
    )
];
has to => (
    isa => $subscriber_array,
    is => 'ro',
    coerce => $subscriber_array->coercion,
    required => 1,
);


sub envelope ($self) {
    return {
        from => $self->from,
        to => [ map { $_->address } $self->to->@* ],
    }
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Sietima::Message - an email message with an envelope

=head1 VERSION

version 1.1.5

=head1 SYNOPSIS

  use Sietima::Message;

  my $msg = Sietima::Message->new({
    mail => $email_mime_object,
    from => 'sender@example.com',
    to => [ 'recipient@example.com', 'also@example.com' ],
  });

=head1 DESCRIPTION

This class pairs a L<< C<Email::MIME> >> object with its
envelope. Objects of this class are usually generated by L<<
C<Sietima::munge_mail>|Sietima/munge_mail >>, and consumed by L<<
C<Sietima::send_message>|Sietima/send_message >>.

=head1 ATTRIBUTES

All attributes are read-only and required.

=head2 C<mail>

An L<< C<Email::MIME> >> object, representing the message.

=head2 C<from>

An L<< C<Email::Address> >> object, coercible from a string,
representing the sender.

=head2 C<to>

An arrayref of L<< C<Sietima::Subscriber> >> objects, each coercible
from a string or an L<< C<Email::Address> >> object, representing the
recipients.

=head1 METHODS

=head2 C<envelope>

  my %envelope = $message->envelope->%*;

Returns a hashref with envelope data, suitable for use with L<<
C<Email::Sender::Transport::send>|Email::Sender::Transport/send >>.

=head1 AUTHOR

Gianni Ceccarelli <dakkar@thenautilus.net>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2025 by Gianni Ceccarelli <dakkar@thenautilus.net>.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
