<?php

namespace App\Services\Auth;

use App\Models\EmailDeliveryLog;
use App\Models\User;
use App\Services\Email\TransactionalEmailSender;
use App\Services\Settings\SettingsService;

class PasswordResetOtpMailer
{
    public function __construct(
        private readonly SettingsService $settings,
        private readonly TransactionalEmailSender $emailSender,
    ) {}

    public function send(User $user, string $otp): void
    {
        $this->emailSender->send(
            toEmail: $user->email,
            toName: $user->name,
            subject: $this->subject(),
            html: $this->html($otp),
            text: $this->text($otp),
            userId: $user->id,
            type: EmailDeliveryLog::TYPE_PASSWORD_RESET_OTP,
            metadata: [
                'purpose' => 'password_reset_otp',
                'expires_minutes' => (int) $this->settings->get('email.password_reset_otp_expires_minutes', 10),
            ],
            resendable: false,
        );
    }

    private function subject(): string
    {
        return (string) $this->settings->get('email.password_reset_otp_subject', 'Your RemoteMatch password reset OTP');
    }

    private function html(string $otp): string
    {
        $expires = (int) $this->settings->get('email.password_reset_otp_expires_minutes', 10);

        return view('emails.auth.password-reset-otp', [
            'subject' => $this->subject(),
            'preheader' => "Your password reset OTP expires in {$expires} minutes.",
            'otp' => $otp,
            'expires' => $expires,
        ])->render();
    }

    private function text(string $otp): string
    {
        $expires = (int) $this->settings->get('email.password_reset_otp_expires_minutes', 10);

        return "Your RemoteMatch password reset OTP is {$otp}. It expires in {$expires} minutes. If you did not request this, ignore this email.";
    }
}
