<?php

namespace App\Http\Controllers\Partner;

use App\Http\Controllers\Controller;
use App\Models\ApiKey;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Inertia\Response;

class ApiKeyController extends Controller
{
    /**
     * Display the API key management page.
     */
    public function index(Request $request): Response
    {
        $user = Auth::user();

        // Get API key regardless of feature flag (feature check can be done in frontend)
        $apiKey = $user->activeApiKey();

        return Inertia::render('Partner/ApiKey', [
            'apiKey' => $apiKey ? [
                'id' => $apiKey->id,
                'name' => $apiKey->name,
                'key' => $apiKey->key,
                'last_used_at' => $apiKey->last_used_at?->toISOString(),
                'expires_at' => $apiKey->expires_at?->toISOString(),
                'is_active' => $apiKey->is_active,
                'created_at' => $apiKey->created_at->toISOString(),
            ] : null,
            'hasApiAccessFeature' => $user->hasFeature('api_access'),
        ]);
    }

    /**
     * Generate a new API key for the partner.
     */
    public function store(Request $request): RedirectResponse
    {
        $user = Auth::user();

        // Check if user has api_access feature
        if (! $user->hasFeature('api_access')) {
            return redirect()->back()->with('error', 'API Access feature is not enabled for your account.');
        }

        // Check if user can create more API keys
        if (! $user->canCreateApiKey()) {
            return redirect()->back()->with('error', 'Anda sudah memiliki API key. Maksimal 1 API key per partner.');
        }

        $validated = $request->validate([
            'name' => ['nullable', 'string', 'max:255'],
        ]);

        // Generate new API key
        $apiKey = ApiKey::create([
            'user_id' => $user->id,
            'name' => $validated['name'] ?? 'Default API Key',
            'key' => ApiKey::generate(),
            'is_active' => true,
        ]);

        return redirect()->back()->with('success', 'API key berhasil dibuat. Pastikan untuk menyimpan key ini dengan aman.');
    }

    /**
     * Regenerate the API key (revoke old and create new).
     */
    public function regenerate(Request $request): RedirectResponse
    {
        $user = Auth::user();

        // Check if user has api_access feature
        if (! $user->hasFeature('api_access')) {
            return redirect()->back()->with('error', 'API Access feature is not enabled for your account.');
        }

        $apiKey = $user->activeApiKey();

        if (! $apiKey) {
            return redirect()->back()->with('error', 'Tidak ada API key yang aktif.');
        }

        // Deactivate old key
        $apiKey->update(['is_active' => false]);

        // Create new key
        $newApiKey = ApiKey::create([
            'user_id' => $user->id,
            'name' => $apiKey->name,
            'key' => ApiKey::generate(),
            'is_active' => true,
        ]);

        return redirect()->back()->with('success', 'API key berhasil di-regenerate. Key lama sudah tidak aktif.');
    }

    /**
     * Revoke (deactivate) the API key.
     */
    public function destroy(Request $request, ApiKey $apiKey): RedirectResponse
    {
        $user = Auth::user();

        // Check if API key belongs to user
        if ($apiKey->user_id !== $user->id) {
            abort(403, 'Unauthorized action.');
        }

        $apiKey->update(['is_active' => false]);

        return redirect()->back()->with('success', 'API key berhasil di-revoke.');
    }
}

