<?php

namespace App\Http\Controllers\Client;

use App\Enums\RecordStatus;
use App\Http\Controllers\Controller;
use App\Models\Withdrawal;
use App\Services\TransactionLogger;
use Illuminate\Http\Request;

class WithdrawalController extends Controller
{
    public function store(Request $request)
    {
        $data = $request->validate([
            'network' => ['required', 'string', 'max:32'],
            'wallet_address' => ['required', 'string', 'max:255'],
            'amount' => ['required', 'numeric', 'min:1'],
        ]);

        $user = $request->user();

        if ($user->balance < $data['amount']) {
            return back()->with('error', 'Insufficient balance.');
        }

        $withdrawal = Withdrawal::create([
            'user_id' => $user->id,
            'network' => $data['network'],
            'wallet_address' => $data['wallet_address'],
            'amount' => $data['amount'],
            'status' => RecordStatus::Pending,
        ]);

        TransactionLogger::fromWithdrawal($withdrawal);

        return redirect()->route('client.home.withdraw')
            ->with('success', 'Withdrawal request submitted. Awaiting admin approval.');
    }
}
