<?php

namespace App\Http\Controllers\API\V1\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\WalletService;
use Illuminate\Http\Request;

class UserManagementController extends Controller
{
    public function __construct(protected WalletService $walletService) {}

    public function index()
    {
        $users = User::with('wallet')->orderBy('created_at', 'desc')->paginate(20);
        return response()->json(['success' => true, 'data' => $users]);
    }

    public function show(int $id)
    {
        $user = User::with(['wallet', 'trades'])->findOrFail($id);
        return response()->json(['success' => true, 'data' => $user]);
    }

    public function updateStatus(Request $request, int $id)
    {
        $user = User::findOrFail($id);
        $user->update(['status' => $request->status]);
        return response()->json(['success' => true, 'data' => $user]);
    }

    public function adjustBalance(Request $request, int $id)
    {
        $user = User::findOrFail($id);
        $wallet = $this->walletService->getOrCreateWallet($user);
        if ($request->amount > 0) {
            $this->walletService->addBalance($wallet, (string) abs($request->amount), 'admin_adjustment', $request->note ?? 'Admin balance adjustment');
        } else {
            $this->walletService->subtractBalance($wallet, (string) abs($request->amount), 'admin_adjustment', $request->note ?? 'Admin balance adjustment');
        }
        return response()->json(['success' => true, 'data' => $wallet->fresh()]);
    }

    public function userTrades(int $id)
    {
        $trades = User::findOrFail($id)->trades()->with('asset')->orderBy('created_at', 'desc')->paginate(20);
        return response()->json(['success' => true, 'data' => $trades]);
    }

    public function userTransactions(int $id)
    {
        $wallet = User::findOrFail($id)->wallet;
        $transactions = $wallet ? $wallet->transactions()->orderBy('created_at', 'desc')->paginate(20) : collect();
        return response()->json(['success' => true, 'data' => $transactions]);
    }
}
