<?php

namespace App\Http\Requests;

use App\Enum\UserAccountMode;
use App\Models\TradeBot;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;

class StartTradeBotRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'trade_bot_id' => ['required', 'exists:trade_bots,id'],
            'wallet_id' => ['required', 'exists:wallets,id'],
            'amount' => ['required', 'numeric', 'min:1'],
            'leverage' => ['required', 'integer', 'in:20,40,60,80,100'],
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $bot = TradeBot::find($this->trade_bot_id);

            if (!$bot) {
                return;
            }

            // Check bot investment limits
            if ($this->amount < $bot->minimum) {
                $validator->errors()->add(
                    'amount',
                    'The amount is below the bot minimum investment.'
                );
            }

            if ($this->amount > $bot->maximum) {
                $validator->errors()->add(
                    'amount',
                    'The amount exceeds the bot maximum investment.'
                );
            }

            // Optional: Prevent demo account usage
            if (Auth::user()->account_mode->value === UserAccountMode::DEMO->value) {
                $validator->errors()->add(
                    'wallet_id',
                    'Trade bots cannot be started on demo accounts.'
                );
            }
        });
    }

    public function messages(): array
    {
        return [
            'trade_bot_id.required' => 'Invalid trading bot selected.',
            'wallet_id.required' => 'Please select a wallet.',
            'amount.required' => 'Investment amount is required.',
            'amount.numeric' => 'Amount must be a valid number.',
            'leverage.in' => 'Invalid leverage selected.',
        ];
    }
}
