<?php

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

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

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

    public function pending()
    {
        $deposits = Deposit::pending()
            ->with(['user', 'wallet'])
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return response()->json(['success' => true, 'data' => $deposits]);
    }

    public function approve(Request $request, int $id)
    {
        $deposit = Deposit::findOrFail($id);

        if (!$deposit->isPending()) {
            return response()->json(['success' => false, 'message' => 'Deposit is not pending'], 400);
        }

        $deposit->markAsCompleted();

        $wallet = $deposit->wallet;
        $this->walletService->addBalance(
            $wallet,
            (string) $deposit->amount,
            'deposit',
            "Manual deposit approved by admin",
            $deposit->id,
            'Deposit'
        );

        return response()->json(['success' => true, 'message' => 'Deposit approved', 'data' => $deposit]);
    }

    public function reject(Request $request, int $id)
    {
        $deposit = Deposit::findOrFail($id);

        if (!$deposit->isPending()) {
            return response()->json(['success' => false, 'message' => 'Deposit is not pending'], 400);
        }

        $deposit->update(['status' => 'failed']);

        return response()->json(['success' => true, 'message' => 'Deposit rejected', 'data' => $deposit]);
    }
}
