<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\ApiKey;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ApiKeyController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        $rows = ApiKey::with('user:id,name,avatar')
            ->orderByDesc('created_at')
            ->get(['id', 'name', 'prefix', 'abilities', 'user_id', 'last_used_at', 'expires_at', 'revoked', 'created_at']);

        return response()->json(['data' => $rows]);
    }

    public function store(Request $request): JsonResponse
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        $data = $request->validate([
            'name' => ['required', 'string', 'max:128'],
            'abilities' => ['nullable', 'array'],
            'abilities.*' => ['string', 'max:64'],
            'expires_in_days' => ['nullable', 'integer', 'min:1', 'max:3650'],
        ]);

        $token = 'noc_api_' . Str::random(48);
        $apiKey = ApiKey::create([
            'name' => $data['name'],
            'token_hash' => hash('sha256', $token),
            'prefix' => substr($token, 0, 8),
            'abilities' => $data['abilities'] ?? ['read'],
            'user_id' => $request->user()->id,
            'expires_at' => isset($data['expires_in_days']) ? now()->addDays($data['expires_in_days']) : null,
        ]);

        ActivityLog::log([
            'action' => 'created API key',
            'target' => $apiKey->name,
            'category' => 'security',
            'severity' => 'high',
        ]);

        return response()->json([
            'data' => $apiKey,
            // Token shown ONCE — never retrievable again. UI must instruct user to copy it now.
            'token' => $token,
            'warning' => 'Copy this token now. It will never be shown again.',
        ], 201);
    }

    public function destroy(Request $request, ApiKey $apiKey): JsonResponse
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        $apiKey->update(['revoked' => true]);

        ActivityLog::log([
            'action' => 'revoked API key',
            'target' => $apiKey->name,
            'category' => 'security',
            'severity' => 'high',
        ]);

        return response()->json(['ok' => true]);
    }
}
