<?php

namespace App\Mail;

use App\Mail\Concerns\RidesALane;
use App\Mail\Concerns\SendsFromMailbox;
use App\Models\User;
use App\Services\Mail\MailCatalogue;
use App\Services\Mail\MailPurpose;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\URL;

/**
 * "Confirm that this address is yours."
 *
 * The first thing anybody ever receives from CluPilot, which is why it is a
 * Mailable in this product's design rather than the framework's default
 * MailMessage with its own logo, button and footer.
 *
 * The link is signed and expires. Both matter: unsigned, anybody who can guess
 * a user id could verify somebody else's address; unexpiring, a forwarded mail
 * from last spring still works.
 */
class VerifyEmailMail extends Mailable implements ShouldQueue
{
    use Queueable, RidesALane, SendsFromMailbox, SerializesModels;

    public function __construct(public User $user)
    {
        $this->mailer(MailCatalogue::mailer('verify-email'));
    }

    public function envelope(): Envelope
    {
        return $this->mailboxEnvelope(MailPurpose::SYSTEM, __('verify_email.subject'), 'verify-email');
    }

    public function content(): Content
    {
        $minutes = (int) config('auth.verification.expire', 60);

        return new Content(view: 'mail.verify-email', with: [
            'name' => $this->user->name,
            'minutes' => $minutes,
            // Built here rather than stored: a signed URL carries its own
            // expiry, so there is no token to keep, none to leak from the
            // database, and none to forget to invalidate.
            'url' => URL::temporarySignedRoute('verification.verify', now()->addMinutes($minutes), [
                'id' => $this->user->getKey(),
                // The address is part of what is signed, so a link stops
                // working the moment somebody changes the address it was
                // issued for.
                'hash' => sha1($this->user->getEmailForVerification()),
            ]),
        ]);
    }
}
