<?php

namespace App\Http\Controllers;

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

class WalletTransferController extends Controller
{
    public function store(Request $request, WalletTransferService $transfers, AuditLogService $audit)
    {
        $payload = $request->validate([
            'receiver_public_id' => ['required', 'string', 'min:5', 'max:12'],
            'amount' => ['required', 'numeric', 'min:1', 'max:50000'],
            'note' => ['nullable', 'string', 'max:500'],
        ]);

        try {
            $transfer = $transfers->transfer(
                $request->user(),
                $payload['receiver_public_id'],
                (int) round(((float) $payload['amount']) * 100),
                $payload['note'] ?? null,
            );

            $audit->record('wallet.transfer_completed', $transfer, [
                'amount_minor' => $transfer->amount_minor,
                'receiver_public_id' => $payload['receiver_public_id'],
            ]);
        } catch (RuntimeException $exception) {
            return back()->withErrors(['transfer' => $exception->getMessage()])->withInput();
        }

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