<?php

namespace App\Services;

use App\Mail\PaymentInvoiceMail;
use App\Models\PaymentTransaction;
use Illuminate\Support\Facades\Mail;
use Throwable;

class PaymentInvoiceEmailer
{
    public function sendIfAvailable(PaymentTransaction $transaction): void
    {
        if ($transaction->invoice_email_sent_at !== null) {
            return;
        }

        if (! $transaction->user || ! $transaction->user->email) {
            return;
        }

        if (! $transaction->invoice_url && ! $transaction->invoice_pdf_url) {
            return;
        }

        try {
            Mail::to($transaction->user->email)->send(
                new PaymentInvoiceMail($transaction->user, $transaction->loadMissing('creditProduct'))
            );
        } catch (Throwable $exception) {
            $transaction->forceFill([
                'error_message' => 'Invoice email failed: '.$exception->getMessage(),
            ])->save();

            return;
        }

        $transaction->forceFill([
            'invoice_email_sent_at' => now(),
        ])->save();
    }
}
