<?php

namespace App\Http\Controllers\Shop;

use App\Http\Controllers\Controller;
use App\Services\ApiCredentialService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ApiCredentialController extends Controller
{
    public function show(Request $request, ApiCredentialService $apiCredentialService): JsonResponse
    {
        $client = $apiCredentialService->ensureDefaultClient($request->user());

        return response()->json([
            'success' => true,
            'data' => [
                'name' => $client->name,
                'public_key' => $client->public_key,
                'status' => $client->status,
                'rate_limit_per_minute' => $client->rate_limit_per_minute,
                'secret_last4' => $client->secret_last4,
                'rotated_at' => optional($client->rotated_at)->toISOString(),
                'signing' => [
                    'headers' => [
                        'X-Api-Key',
                        'X-Timestamp',
                        'X-Nonce',
                        'X-Signature',
                        'X-Idempotency-Key',
                    ],
                    'signature_format' => "HMAC_SHA256(METHOD\\nPATH\\nTIMESTAMP\\nNONCE\\nSHA256(BODY), secret)",
                ],
            ],
        ]);
    }

    public function rotate(Request $request, ApiCredentialService $apiCredentialService): JsonResponse
    {
        $client = $apiCredentialService->ensureDefaultClient($request->user());
        [, $newSecret] = $apiCredentialService->rotateSecret($client);

        return response()->json([
            'success' => true,
            'message' => 'API secret rotated. Save this secret now; it will not be shown again.',
            'data' => [
                'public_key' => $client->public_key,
                'secret' => $newSecret,
                'secret_last4' => substr($newSecret, -4),
            ],
        ]);
    }
}
