<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PaymentGateway;
use App\Services\PaymentGatewayCredentialService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class AdminPaymentGatewayController extends Controller
{
    public function __construct(
        private readonly PaymentGatewayCredentialService $credentials
    ) {
    }

    public function index(): View
    {
        $gateways = PaymentGateway::query()
            ->orderBy('priority')
            ->orderBy('name')
            ->get();

        return view('admin.payment-gateways.index', [
            'gateways' => $gateways,
            'maskedCredentials' => $gateways
                ->mapWithKeys(fn (PaymentGateway $gateway): array => [
                    $gateway->id => $this->credentials->maskedCredentials($gateway),
                ]),
        ]);
    }

    public function create(): RedirectResponse
    {
        return redirect()
            ->route('admin.payment-gateways.index')
            ->with('error', 'Default payment gateways are managed from the gateway settings page.');
    }

    public function store(Request $request): RedirectResponse
    {
        return redirect()
            ->route('admin.payment-gateways.index')
            ->with('error', 'Creating custom payment gateways is not enabled yet.');
    }

    public function show(PaymentGateway $paymentGateway): View
    {
        return view('admin.payment-gateways.show', [
            'gateway' => $paymentGateway,
            'maskedCredentials' => $this->credentials->maskedCredentials($paymentGateway),
        ]);
    }

    public function edit(PaymentGateway $paymentGateway): View
    {
        return view('admin.payment-gateways.edit', [
            'gateway' => $paymentGateway,
            'maskedCredentials' => $this->credentials->maskedCredentials($paymentGateway),
        ]);
    }

    public function update(Request $request, PaymentGateway $paymentGateway): RedirectResponse
    {
        $data = $request->validate([
            'status' => ['required', Rule::in([PaymentGateway::STATUS_ACTIVE, PaymentGateway::STATUS_INACTIVE])],
            'public_key' => ['nullable', 'string', 'max:1000'],
            'secret_key' => ['nullable', 'string', 'max:2000'],
            'webhook_secret' => ['nullable', 'string', 'max:2000'],
            'is_test_mode' => ['nullable', 'boolean'],
            'priority' => ['required', 'integer', 'min:0', 'max:9999'],
        ]);

        $updateData = [
            'status' => $data['status'],
            'public_key' => $data['public_key'] ?? null,
            'is_test_mode' => $request->boolean('is_test_mode'),
            'priority' => $data['priority'],
        ];

        if (filled($data['secret_key'] ?? null)) {
            $updateData['secret_key'] = $data['secret_key'];
        }

        if (filled($data['webhook_secret'] ?? null)) {
            $updateData['webhook_secret'] = $data['webhook_secret'];
        }

        $paymentGateway->update($updateData);

        return redirect()
            ->route('admin.payment-gateways.show', $paymentGateway)
            ->with('success', 'Payment gateway settings updated successfully.');
    }

    public function destroy(PaymentGateway $paymentGateway): RedirectResponse
    {
        return redirect()
            ->route('admin.payment-gateways.index')
            ->with('error', 'Payment gateways are prepared system records and cannot be deleted from this page.');
    }

    public function toggleStatus(PaymentGateway $paymentGateway): RedirectResponse
    {
        $paymentGateway->update([
            'status' => $paymentGateway->isActive()
                ? PaymentGateway::STATUS_INACTIVE
                : PaymentGateway::STATUS_ACTIVE,
        ]);

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

    public function test(PaymentGateway $paymentGateway): RedirectResponse
    {
        return back()->with('success', "{$paymentGateway->name} connection test placeholder is ready. Real API testing will be added when keys and provider integration are connected.");
    }
}
