<?php

namespace App\Modules\Payment;

use App\Facades\Settings;
use Illuminate\Support\Facades\Log;
use Mtc\Checkout\Contracts\InvoiceRepositoryContract;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\VehicleReservations\Reservation;

class Stripe extends \Mtc\Stripe\Stripe
{
    /**
     * @param InvoiceRepositoryContract $invoice
     * @return string
     */
    #[\Override]
    public function paymentDescription(InvoiceRepositoryContract $invoice): string
    {
        return $this->getDescriptionFromFormat($invoice)
            ?? 'Payment on ' . config('app.name') . ' order ' . $invoice->getReference();
    }

    /**
     * Build a description from a format setting.
     * Returns null if any steps fail.
     *
     * @param InvoiceRepositoryContract $invoice
     * @return string|null
     */
    protected function getDescriptionFromFormat(InvoiceRepositoryContract $invoice): ?string
    {
        try {
            $format = Settings::get('sales-stripe-payment-description-format');

            if (empty($format)) {
                return null;
            }

            $invoice_model = $invoice->getModel();
            $reservation = Reservation::find($invoice_model->payable_id) ?? null;
            $vehicle = Vehicle::find($reservation->vehicle_id) ?? null;

            $replacements = [
                '{make}' => $vehicle->make?->name,
                '{model}' => $vehicle->model?->name,
                '{vrm}' => $vehicle->vrm_condensed,
                '{derivative}' => $vehicle->derivative,
            ];

            return str_ireplace(array_keys($replacements), $replacements, $format);
        } catch (\Exception $exception) {
            Log::error('Unable to create description for invoice with id ' . $invoice->getId(), [
                'invoice_id' => $invoice->getId(),
                'tenant_id' => tenant('id'),
                'error message' => $exception->getMessage(),
            ]);

            return null;
        }
    }
}
