<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ApiKey;
use App\Models\ApiKeyIp;
use App\Models\ApiLog;
use App\Services\AdminActivityLogger;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ApiController extends Controller
{
    public function index(): View
    {
        return view('admin.api', [
            'keys' => ApiKey::query()->with('ips')->latest()->get(),
            'logs' => ApiLog::query()->latest()->limit(50)->get(),
            'newKey' => session('api_plain_key'),
        ]);
    }

    public function store(Request $request, AdminActivityLogger $logger): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:191'],
        ]);

        $plain = Str::random(40);
        $hash = hash('sha256', $plain);

        $key = ApiKey::query()->create([
            'name' => $validated['name'],
            'key_hash' => $hash,
            'is_active' => true,
            'created_by' => auth()->id(),
        ]);

        $logger->log('api.key.create', ApiKey::class, $key->id);

        return back()->with('api_plain_key', $plain)->with('status', 'API key created. Copy it now; it will not be shown again.');
    }

    public function revoke(ApiKey $key, AdminActivityLogger $logger): RedirectResponse
    {
        $key->is_active = false;
        $key->save();

        $logger->log('api.key.revoke', ApiKey::class, $key->id);

        return back()->with('status', 'API key revoked.');
    }

    public function addIp(Request $request, ApiKey $key, AdminActivityLogger $logger): RedirectResponse
    {
        $validated = $request->validate([
            'ip_address' => ['required', 'string', 'max:45'],
        ]);

        ApiKeyIp::query()->firstOrCreate([
            'api_key_id' => $key->id,
            'ip_address' => $validated['ip_address'],
        ]);

        $logger->log('api.key.ip.add', ApiKey::class, $key->id, ['ip' => $validated['ip_address']]);

        return back()->with('status', 'IP whitelisted.');
    }

    public function removeIp(ApiKey $key, ApiKeyIp $ip, AdminActivityLogger $logger): RedirectResponse
    {
        if ((int) $ip->api_key_id !== (int) $key->id) {
            return back()->withErrors(['ip' => 'IP does not belong to this key.']);
        }

        $ip->delete();
        $logger->log('api.key.ip.remove', ApiKey::class, $key->id, ['ip' => $ip->ip_address]);

        return back()->with('status', 'IP removed.');
    }
}
