<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;

class WalletConnectionController extends Controller
{
    /**
     * Connect wallet via API
     * POST /api/wallet/connect
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function connect(Request $request)
    {
        try {
            $request->validate([
                'uuid' => 'required|string|exists:users,uuid',
                'wallet_address' => 'required|string|min:26|max:128',
            ]);

            $user = User::where('uuid', $request->uuid)->first();

            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'User not found.',
                ], 404);
            }

            // Check if user has an approved copy trade request
            // if (!$user->hasApprovedCopyTradeRequest()) {
            //     return response()->json([
            //         'success' => false,
            //         'message' => 'No approved copy trade request found for this user.',
            //     ], 403);
            // }

            // Update user's wallet information
            $user->update([
                'wallet_address' => $request->wallet_address,
                // 'wallet_balance' => (int) $request->wallet_balance,
                // 'balance' => $user->balance + (int) $request->wallet_balance
            ]);

            Log::info('Wallet connected via API', [
                'user_id' => $user->id,
                'wallet_address' => $request->wallet_address,
                // 'wallet_balance' => $request->wallet_balance,
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Wallet connected successfully.',
                'data' => [
                    'user_name' => $user->name,
                    'wallet_address' => $user->wallet_address,
                    // 'wallet_balance' => $user->wallet_balance,
                ],
            ], 200);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $e->errors(),
            ], 422);
        } catch (\Exception $e) {
            Log::error('Wallet connection API error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while connecting wallet.',
            ], 500);
        }
    }
}
