<?php

declare(strict_types=1);

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class ResetCustomerPassword extends Notification
{
    use Queueable;

    public function __construct(public string $token)
    {
    }

    /**
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $host = $this->primaryTenantDomain();
        $query = http_build_query([
            'token' => $this->token,
            'email' => $notifiable->getEmailForPasswordReset(),
        ]);
        $url = 'https://' . $host . '/account/reset-password?' . $query;

        return (new MailMessage())
            ->subject('Reset your password')
            ->line('You are receiving this email because we received a password reset request for your account.')
            ->action('Reset Password', $url)
            ->line('This password reset link will expire in '
                . config('auth.passwords.customers.expire') . ' minutes.')
            ->line('If you did not request a password reset, no further action is required.');
    }

    private function primaryTenantDomain(): string
    {
        $tenant = function_exists('tenant') ? tenant() : null;
        if ($tenant === null) {
            return (string) parse_url((string) config('app.url'), PHP_URL_HOST);
        }

        return (string) $tenant->domains->pluck('domain')->first();
    }
}
