<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\TradingSymbol;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class TradingSymbolController extends Controller
{
    public function index(): View
    {
        return view('admin.trading-symbols.index', [
            'symbols' => TradingSymbol::query()
                ->orderBy('category')
                ->orderBy('symbol')
                ->paginate(15),
        ]);
    }

    public function create(): View
    {
        return view('admin.trading-symbols.create', [
            'symbol' => new TradingSymbol([
                'category' => 'forex',
                'quote_currency' => 'USD',
                'contract_size' => 100000,
                'pip_size' => 0.0001,
                'default_price' => 1,
                'is_active' => true,
            ]),
            'categories' => $this->categories(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $this->validatedData($request);
        $data['symbol'] = strtoupper($data['symbol']);
        $data['base_currency'] = filled($data['base_currency'] ?? null) ? strtoupper($data['base_currency']) : null;
        $data['quote_currency'] = strtoupper($data['quote_currency']);
        $data['is_active'] = $request->boolean('is_active');

        $symbol = TradingSymbol::create($data);

        return redirect()
            ->route('admin.trading-symbols.show', $symbol)
            ->with('success', 'Trading symbol created successfully.');
    }

    public function show(TradingSymbol $tradingSymbol): View
    {
        return view('admin.trading-symbols.show', [
            'symbol' => $tradingSymbol,
        ]);
    }

    public function edit(TradingSymbol $tradingSymbol): View
    {
        return view('admin.trading-symbols.edit', [
            'symbol' => $tradingSymbol,
            'categories' => $this->categories(),
        ]);
    }

    public function update(Request $request, TradingSymbol $tradingSymbol): RedirectResponse
    {
        $data = $this->validatedData($request, $tradingSymbol);
        $data['symbol'] = strtoupper($data['symbol']);
        $data['base_currency'] = filled($data['base_currency'] ?? null) ? strtoupper($data['base_currency']) : null;
        $data['quote_currency'] = strtoupper($data['quote_currency']);
        $data['is_active'] = $request->boolean('is_active');

        $tradingSymbol->update($data);

        return redirect()
            ->route('admin.trading-symbols.show', $tradingSymbol)
            ->with('success', 'Trading symbol updated successfully.');
    }

    public function destroy(TradingSymbol $tradingSymbol): RedirectResponse
    {
        $tradingSymbol->delete();

        return redirect()
            ->route('admin.trading-symbols.index')
            ->with('success', 'Trading symbol deleted successfully.');
    }

    public function toggleStatus(TradingSymbol $tradingSymbol): RedirectResponse
    {
        $tradingSymbol->update([
            'is_active' => ! $tradingSymbol->is_active,
        ]);

        return back()->with('success', 'Trading symbol status updated successfully.');
    }

    private function validatedData(Request $request, ?TradingSymbol $tradingSymbol = null): array
    {
        return $request->validate([
            'symbol' => [
                'required',
                'string',
                'max:30',
                Rule::unique('trading_symbols', 'symbol')->ignore($tradingSymbol),
            ],
            'display_name' => ['required', 'string', 'max:255'],
            'category' => ['required', Rule::in(array_keys($this->categories()))],
            'base_currency' => ['nullable', 'string', 'max:10'],
            'quote_currency' => ['required', 'string', 'max:10'],
            'contract_size' => ['required', 'numeric', 'min:0.0001'],
            'pip_size' => ['required', 'numeric', 'min:0.000001'],
            'default_price' => ['required', 'numeric', 'min:0.000001'],
            'is_active' => ['nullable', 'boolean'],
        ]);
    }

    private function categories(): array
    {
        return [
            'forex' => 'Forex',
            'metal' => 'Metal',
            'index' => 'Index',
            'commodity' => 'Commodity',
        ];
    }
}
