<?php

namespace App\Http\Controllers;

use App\Services\AuditLogService;
use App\Services\VoucherService;
use Illuminate\Http\Request;
use RuntimeException;

class VoucherRedeemController extends Controller
{
    public function store(Request $request, VoucherService $vouchers, AuditLogService $audit)
    {
        $payload = $request->validate([
            'voucher_code' => ['required', 'string', 'max:64'],
        ]);

        try {
            $redemption = $vouchers->redeem($request->user(), $payload['voucher_code']);
            $audit->record('voucher.redeemed', $redemption, [
                'voucher_code' => strtoupper(trim($payload['voucher_code'])),
                'amount_minor' => $redemption->amount_minor,
            ]);
        } catch (RuntimeException $exception) {
            return back()->withErrors(['voucher' => $exception->getMessage()])->withInput();
        }

        return back()->with('status', 'تم شحن الرصيد من الكود بنجاح.');
    }
}
