package dev.rheinsw.shared.mail;

import dev.rheinsw.shared.mail.dto.MailRequest;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author Thatsaphorn Atchariyaphap
 * @since 22.04.25
 */
@Service
@RequiredArgsConstructor
public class MailServiceClient {

    private static final Logger log = LoggerFactory.getLogger(MailServiceClient.class);

    private final RestTemplate restTemplate;

    private static final String MAIL_ENDPOINT = "http://gateway/api/mail";

    @Value("${INTERNAL_API_KEY}")
    private String internalApiKey;

    @Async
    public void sendMail(String email, String subject, String userMessage) {
        MailRequest request = new MailRequest(email, subject, userMessage);
        postEmail(request);
    }

    private void postEmail(MailRequest request) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Internal-Auth", internalApiKey);

            HttpEntity<MailRequest> entity = new HttpEntity<>(request, headers);

            restTemplate.postForEntity(MAIL_ENDPOINT + "/send", entity, String.class);
        } catch (Exception e) {
            log.error("Failed to send email to {}: {}", request.getTo(), e.getMessage());
        }
    }

}
