package com.cameleer.server.app.controller;

import com.cameleer.server.core.license.LicenseGate;
import com.cameleer.server.core.license.LicenseInfo;
import com.cameleer.server.core.license.LicenseValidator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/v1/admin/license")
@PreAuthorize("hasRole('ADMIN')")
@Tag(name = "License Admin", description = "License management")
public class LicenseAdminController {

    private final LicenseGate licenseGate;
    private final String licensePublicKey;
    private final String tenantId;

    public LicenseAdminController(LicenseGate licenseGate,
                                   @Value("${cameleer.server.license.publickey:}") String licensePublicKey,
                                   @Value("${cameleer.server.tenant.id:default}") String tenantId) {
        this.licenseGate = licenseGate;
        this.licensePublicKey = licensePublicKey;
        this.tenantId = tenantId;
    }

    @GetMapping
    @Operation(summary = "Get current license info")
    public ResponseEntity<LicenseInfo> getCurrent() {
        return ResponseEntity.ok(licenseGate.getCurrent());
    }

    record UpdateLicenseRequest(String token) {}

    @PostMapping
    @Operation(summary = "Update license token at runtime")
    public ResponseEntity<?> update(@RequestBody UpdateLicenseRequest request) {
        if (licensePublicKey == null || licensePublicKey.isBlank()) {
            return ResponseEntity.badRequest().body(Map.of("error", "No license public key configured"));
        }
        try {
            LicenseValidator validator = new LicenseValidator(licensePublicKey, tenantId);
            LicenseInfo info = validator.validate(request.token());
            licenseGate.load(info);
            return ResponseEntity.ok(info);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
}
