<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\RateLimitSetting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RateLimitController extends Controller
{
    public function index(): JsonResponse
    {
        $settings = RateLimitSetting::orderByRaw('endpoint ASC NULLS FIRST')->get();

        $global = $settings->firstWhere('endpoint', null);

        return response()->json([
            'global' => $global,
            'endpoints' => $settings->whereNotNull('endpoint')->values(),
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'endpoint' => 'required|string|max:255|unique:rate_limit_settings,endpoint',
            'max_attempts' => 'required|integer|min:1|max:10000',
            'decay_seconds' => 'required|integer|min:1|max:86400',
            'is_enabled' => 'boolean',
            'description' => 'nullable|string|max:255',
        ]);

        $setting = RateLimitSetting::create($validated);
        RateLimitSetting::clearCache();

        return response()->json($setting, 201);
    }

    public function update(Request $request, RateLimitSetting $rateLimitSetting): JsonResponse
    {
        $rules = [
            'max_attempts' => 'sometimes|integer|min:1|max:10000',
            'decay_seconds' => 'sometimes|integer|min:1|max:86400',
            'is_enabled' => 'sometimes|boolean',
            'description' => 'nullable|string|max:255',
        ];

        if ($rateLimitSetting->endpoint !== null) {
            $rules['endpoint'] = 'sometimes|string|max:255|unique:rate_limit_settings,endpoint,' . $rateLimitSetting->id;
        }

        $validated = $request->validate($rules);

        $rateLimitSetting->update($validated);
        RateLimitSetting::clearCache();

        return response()->json($rateLimitSetting);
    }

    public function destroy(RateLimitSetting $rateLimitSetting): JsonResponse
    {
        if ($rateLimitSetting->endpoint === null) {
            return response()->json([
                'message' => 'Global ayar silinemez. Devre dışı bırakabilirsiniz.',
            ], 422);
        }

        $rateLimitSetting->delete();
        RateLimitSetting::clearCache();

        return response()->json(['message' => 'Ayar silindi.']);
    }

    public function toggleGlobal(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'is_enabled' => 'required|boolean',
        ]);

        $global = RateLimitSetting::whereNull('endpoint')->first();

        if (!$global) {
            $global = RateLimitSetting::create([
                'endpoint' => null,
                'max_attempts' => 100,
                'decay_seconds' => 60,
                'is_enabled' => $validated['is_enabled'],
                'description' => 'Global varsayılan ayar',
            ]);
        } else {
            $global->update(['is_enabled' => $validated['is_enabled']]);
        }

        RateLimitSetting::clearCache();

        return response()->json($global);
    }
}
