<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\ApiKey;
use Illuminate\Http\Request;

class ApiKeyController extends Controller
{
    /**
     * GET /api/api-keys
     */
    public function index(Request $request)
    {
        $tenant = $request->input('_tenant') ?? $request->user()->tenant;

        // API keys require agency plan
        $limits = $tenant->getPlanLimits();
        if (!$limits['api_access']) {
            return response()->json(['error' => 'API access requires Agency plan.'], 403);
        }

        $keys = ApiKey::where('tenant_id', $tenant->id)
            ->orderByDesc('created_at')
            ->get()
            ->map(fn($k) => [
                'id'          => $k->id,
                'name'        => $k->name,
                'key_prefix'  => $k->key_prefix . '...',
                'created_at'  => $k->created_at?->toIso8601String(),
                'last_used_at'=> $k->last_used_at?->toIso8601String(),
                'usage_count' => $k->usage_count,
                'is_active'   => $k->is_active,
                'expires_at'  => $k->expires_at?->toIso8601String(),
            ]);

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

    /**
     * POST /api/api-keys
     */
    public function store(Request $request)
    {
        $tenant = $request->input('_tenant') ?? $request->user()->tenant;
        $limits = $tenant->getPlanLimits();

        if (!$limits['api_access']) {
            return response()->json(['error' => 'API access requires Agency plan.'], 403);
        }

        $validated = $request->validate([
            'name'       => 'required|string|max:100',
            'expires_at' => 'nullable|date|after:today',
        ]);

        [$plainKey, $prefix, $hash] = ApiKey::generateKey();

        $key = ApiKey::create([
            'tenant_id'  => $tenant->id,
            'user_id'    => $request->user()->id,
            'name'       => $validated['name'],
            'key_hash'   => $hash,
            'key_prefix' => $prefix,
            'is_active'  => true,
            'usage_count'=> 0,
            'expires_at' => $validated['expires_at'] ?? null,
        ]);

        return response()->json([
            'id'         => $key->id,
            'name'       => $key->name,
            'key'        => $plainKey, // shown only once
            'key_prefix' => $prefix,
            'created_at' => $key->created_at?->toIso8601String(),
        ], 201);
    }

    /**
     * DELETE /api/api-keys/{id}
     */
    public function destroy(Request $request, int $id)
    {
        $tenant = $request->input('_tenant') ?? $request->user()->tenant;
        $key    = ApiKey::where('id', $id)->where('tenant_id', $tenant->id)->firstOrFail();
        $key->update(['is_active' => false]);
        return response()->json(['message' => 'API key revoked.']);
    }
}
