<?php

namespace App\Http\Controllers\Dashboard\User;

use App\Models\User;
use App\Models\Wallet;
use App\Models\TradeBot;
use App\Enum\WalletStatus;
use App\Models\Transaction;
use App\Models\TradeBotUser;
use Illuminate\Http\Request;
use App\Enum\TransactionType;
use App\Enum\TransactionMethod;
use App\Enum\TransactionStatus;
use App\Enum\TransactionDirection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\StartTradeBotRequest;

class TradeBotController extends Controller
{
    public function __construct()
    {
        $this->middleware(['registeredUser', 'kycVerification']);
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $user = Auth::user();

        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('user.dashboard')],
            ['label' => 'Get Started With Trade Bot', 'active' => true]
        ];

        $tradeBots = TradeBot::latest()->get();

        $wallets = Wallet::where('status', WalletStatus::ACTIVE)->get();

        $data = [
            'title' => 'Get Started With Trade Bot',
            'user' => $user,
            'breadcrumbs' => $breadcrumbs,
            'tradeBots' => $tradeBots,
            'wallets' => $wallets
        ];

        return view('dashboard.user.trade_bot.index', $data);
    }

    public function create()
    {
        $user = Auth::user();

        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('user.dashboard')],
            ['label' => 'Get Started With Trade Bot', 'url' => route('user.trade.bot.index')],
            ['label' => 'Trade Bots', 'active' => true]
        ];

        $tradeBots = TradeBot::latest()->get();

        $wallets = Wallet::where('status', WalletStatus::ACTIVE)->get();

        $data = [
            'title' => 'Trade Bots',
            'user' => $user,
            'breadcrumbs' => $breadcrumbs,
            'tradeBots' => $tradeBots,
            'wallets' => $wallets
        ];

        return view('dashboard.user.trade_bot.create', $data);
    }

    public function connect(Request $request)
    {
        $request->validate([
            'api_key' => 'required',
            'secret_key' => 'required',
        ]);

        try {
            $user = Auth::user();

            if ($user->api_key == $request->api_key && $user->secret_key == $request->secret_key) {
                return redirect()->route('user.trade.bot.create')->with('success', 'Trade bot connected successfully.');
            } else {
                return redirect()->route('user.trade.bot.index')->with('error', 'Incorrect API or Secret key. Please try again.');
            }
        } catch (\Throwable $e) {

            Log::error('Trade bot connection failed', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id(),
            ]);

            return redirect()->route('user.trade.bot.index')->with('error', 'Trade bot connection failed. Please try again.');
        }
    }

    public function store(StartTradeBotRequest $request)
    {
        $user = Auth::user();
        try {

            if ($user->balance < $request->amount) {
                return redirect()->back()->with('error', 'Insufficient balance!');
            }

            DB::transaction(function () use ($request, $user) {
                TradeBotUser::create([
                    'user_id' => $user->id,
                    'trade_bot_id' => $request->trade_bot_id,
                    'amount' => $request->amount,
                    'leverage' => $request->leverage,
                    'started_at' => now(),
                    'meta' => [
                        'request' => $request->all(),
                        'initial_balance' => $request->amount
                    ],
                ]);

                // Deduct balance
                $user->balance -= $request->amount;
                $user->save();

                $this->saveTransaction($user->id, $request->amount);
            });

            return redirect()
                ->back()
                ->with('success', 'Trade bot started successfully.');
        } catch (\Throwable $e) {

            Log::error('Trade bot start failed', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id(),
            ]);

            return redirect()
                ->back()
                ->with('error', 'Trade bot start failed. Please try again.');
        }
    }

    protected function saveTransaction($userID, $amount)
    {
        Transaction::create([
            'user_id' => $userID,
            'type' => TransactionType::WITHDRAW,
            'direction' => TransactionDirection::DEBIT,
            'description' => 'Trade bot withdraw',
            'amount' => $amount,
            'method' => TransactionMethod::CRYPTO,
            'transaction_at' => now(),
            'reference_id' => generateReferenceId(),
            'status' => TransactionStatus::COMPLETED
        ]);
    }
}
