<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\License\LicenseValidationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class LicenseController extends Controller
{
    public function __construct(private LicenseValidationService $validator) {}

    private function statusFor(array $result): int
    {
        if (! isset($result['error'])) return 200;
        return match($result['error']) {
            'BRUTE_FORCE_BLOCKED' => 429,
            default               => 422,
        };
    }

    public function activate(Request $request): JsonResponse
    {
        $data   = array_merge($request->all(), ['ip' => $request->ip()]);
        $result = $this->validator->activate($data);
        return response()->json($result, $this->statusFor($result));
    }

    public function deactivate(Request $request): JsonResponse
    {
        $data   = array_merge($request->all(), ['ip' => $request->ip()]);
        $result = $this->validator->deactivate($data);
        return response()->json($result, $this->statusFor($result));
    }

    public function validate(Request $request): JsonResponse
    {
        $data   = array_merge($request->all(), ['ip' => $request->ip()]);
        $result = $this->validator->validate($data);
        return response()->json($result, $this->statusFor($result));
    }

    public function checkUpdate(Request $request): JsonResponse
    {
        $data   = array_merge($request->all(), ['ip' => $request->ip()]);
        $result = $this->validator->checkUpdate($data);
        return response()->json($result, $this->statusFor($result));
    }

    public function heartbeat(Request $request): JsonResponse
    {
        $data   = array_merge($request->all(), ['ip' => $request->ip()]);
        $result = $this->validator->heartbeat($data);
        return response()->json($result, $this->statusFor($result));
    }

    public function report(Request $request): JsonResponse
    {
        // Accept telemetry reports from clients — store for analytics
        return response()->json(['received' => true, 'timestamp' => now()->toIso8601String()]);
    }
}
