<?php

namespace App\Http\Controllers;

use App\Models\ApiKey;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class ApiKeyController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['nullable', 'string', 'max:100'],
        ]);

        $result = ApiKey::generateKeyForUser(
            $request->user()->id,
            $validated['name'] ?? null
        );

        return redirect()->route('settings.edit')
            ->with('status', 'api-key-created')
            ->with('api_key_plain', $result['plain'])
            ->with('api_key_prefix', $result['prefix']);
    }

    public function destroy(Request $request, ApiKey $apiKey): RedirectResponse
    {
        if ($apiKey->user_id !== $request->user()->id) {
            throw ValidationException::withMessages(['api_key' => [__('Unauthorized.')]]);
        }

        $apiKey->delete();

        return redirect()->route('settings.edit')
            ->with('status', 'api-key-deleted');
    }
}
