package com.smyhub.store.mengyastorebackendjava.controller;

import com.smyhub.store.mengyastorebackendjava.config.AppProperties;
import com.smyhub.store.mengyastorebackendjava.dto.response.ApiResponse;
import com.smyhub.store.mengyastorebackendjava.dto.response.HealthResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/api")
public class HealthController {

    private final AppProperties appProperties;

    @Autowired(required = false)
    private RabbitTemplate rabbitTemplate;

    public HealthController(AppProperties appProperties) {
        this.appProperties = appProperties;
    }

    @GetMapping("/health")
    public ResponseEntity<ApiResponse<HealthResponse>> health() {
        HealthResponse body = HealthResponse.builder()
                .status("ok")
                .rabbitmq(checkRabbitMQ())
                .build();
        return ResponseEntity.ok(ApiResponse.ok(body));
    }

    private String checkRabbitMQ() {
        if (!appProperties.isRabbitmqEnabled()) {
            return "disabled";
        }
        if (rabbitTemplate == null) {
            return "disabled";
        }
        try {
            rabbitTemplate.execute(channel -> {
                channel.basicQos(1);
                return null;
            });
            return "ok";
        } catch (Exception e) {
            log.debug("[Health] RabbitMQ ping failed: {}", e.getMessage());
            return "error";
        }
    }
}
