package dev.rheinsw.contactService.controller;

import dev.rheinsw.contactService.dto.ContactRequestDto;
import dev.rheinsw.contactService.model.ContactRequest;
import dev.rheinsw.contactService.repository.ContactRequestsRepo;
import dev.rheinsw.contactService.service.HCaptchaValidator;
import dev.rheinsw.shared.mail.MailServiceClient;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * REST controller to handle contact form submissions.
 *
 * @author Thatsaphorn Atchariyaphap
 * @since 21.04.25
 */
@RestController
@AllArgsConstructor
@RequestMapping("/contact")
public class ContactController {

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

    private final HCaptchaValidator captchaValidator;
    private final ContactRequestsRepo contactRepository;
    private final MailServiceClient mailServiceClient;

    @PostMapping
    public ResponseEntity<String> submitContact(@RequestBody ContactRequestDto request) {
        log.info("Received contact form from: {}", request.name);
        log.debug("Captcha token: {}", request.captcha);
        log.info("Message: {}", request.message);

        if (request.email != null) {
            log.info("Reply to: {} ({})", request.email, request.name);
        }

        if (!isValidCaptcha(request.captcha)) {
            log.warn("Captcha verification failed for {}", request.email);
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Captcha verification failed");
        }

        ContactRequest message = new ContactRequest()
                .setName(request.name)
                .setEmail(request.email)
                .setMessage(request.message)
                .setCompany(request.company)
                .setPhone(request.phone)
                .setWebsite(request.website)
                .setCaptchaToken(request.captcha)
                .setSubmittedAt(LocalDateTime.now());

        contactRepository.save(message);

        notifyContactAndTeam(request);

        return ResponseEntity.ok("Contact form submitted successfully");
    }

    private boolean isValidCaptcha(String captcha) {
        return "10000000-aaaa-bbbb-cccc-000000000001".equals(captcha) || captchaValidator.isValid(captcha);
    }

    private void notifyContactAndTeam(ContactRequestDto request) {
        // User confirmation
        String userSubject = "Kontaktanfrage erhalten";
        String userBody = """
                Hallo %s,
                
                wir haben Ihre Nachricht erhalten und melden uns schnellstmöglich bei Ihnen.
                
                Ihre Nachricht:
                %s
                
                Mit freundlichen Grüßen
                Rhein Software
                """.formatted(request.name, request.message);

        mailServiceClient.sendMail(request.email, userSubject, userBody);

        // Team notification
        String teamSubject = "Neue Kontaktanfrage";
        String teamBody = """
                Neue Kontaktanfrage von: %s
                E-Mail: %s
                Unternehmen: %s
                Telefonnummer: %s
                Webseite: %s
                
                Nachricht:
                %s
                """.formatted(
                request.name,
                request.email,
                safe(request.company),
                safe(request.phone),
                safe(request.website),
                request.message
        );

        mailServiceClient.sendMail("rhein.software@gmail.com", teamSubject, teamBody);
    }

    private String safe(String value) {
        return value != null ? value : "-";
    }

}
