package com.erp.systemtool.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * Notification Service
 * 
 * Sends notifications via various channels (DingTalk, SMS, Email).
 * Used by MonitoringService for alerts.
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NotificationService {

    private final RestTemplate restTemplate = new RestTemplate();

    @Value("${notification.dingtalk.webhook:}")
    private String dingTalkWebhook;

    @Value("${notification.dingtalk.enabled:false}")
    private boolean dingTalkEnabled;

    /**
     * Send DingTalk notification
     */
    public void sendDingTalkNotification(String markdown) {
        if (!dingTalkEnabled || dingTalkWebhook == null || dingTalkWebhook.isEmpty()) {
            log.debug("DingTalk notification skipped - not configured");
            return;
        }

        try {
            String url = dingTalkWebhook;
            
            // Build DingTalk markdown message
            String json = String.format(
                "{\"msgtype\":\"markdown\",\"markdown\":{\"title\":\"System Alert\",\"text\":\"%s\"}}",
                markdown.replace("\"", "\\\"").replace("\n", "\\n")
            );

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> request = new HttpEntity<>(json, headers);

            restTemplate.postForEntity(url, request, String.class);
            log.info("DingTalk notification sent successfully");
        } catch (Exception e) {
            log.error("Failed to send DingTalk notification: {}", e.getMessage());
        }
    }

    /**
     * Send SMS notification
     */
    public void sendSmsNotification(String phone, String message) {
        // TODO: Implement SMS integration
        log.info("SMS notification to {}: {}", phone, message);
    }

    /**
     * Send email notification
     */
    public void sendEmailNotification(String to, String subject, String content) {
        // TODO: Implement email integration
        log.info("Email notification to {}: {}", to, subject);
    }
}
