package com.cameleer.server.app.license;

import com.cameleer.server.core.license.LicenseGate;
import com.cameleer.server.core.license.LicenseInfo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.LinkedHashMap;
import java.util.Map;

@ControllerAdvice
public class LicenseExceptionAdvice {

    private final LicenseGate gate;

    public LicenseExceptionAdvice(LicenseGate gate) {
        this.gate = gate;
    }

    @ExceptionHandler(LicenseCapExceededException.class)
    public ResponseEntity<Map<String, Object>> handle(LicenseCapExceededException e) {
        var state = gate.getState();
        LicenseInfo info = gate.getCurrent();
        String reason = gate.getInvalidReason();
        Map<String, Object> body = new LinkedHashMap<>();
        body.put("error", "license cap reached");
        body.put("limit", e.limitKey());
        body.put("current", e.current());
        body.put("cap", e.cap());
        body.put("state", state.name());
        body.put("message", LicenseMessageRenderer.forCap(state, info, e.limitKey(), e.current(), e.cap(), reason));
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body(body);
    }
}
