package dev.rheinsw.server.contact.usecase;

import dev.rheinsw.server.contact.model.ContactRequest;
import dev.rheinsw.server.contact.model.ContactRequestDto;
import dev.rheinsw.server.contact.repository.ContactRequestsRepo;
import dev.rheinsw.server.contact.util.HCaptchaValidator;
import dev.rheinsw.server.mail.domain.MailRequest;
import dev.rheinsw.server.mail.usecase.SendMailUseCase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author Thatsaphorn Atchariyaphap
 * @since 04.05.25
 */
@Service
public class SubmitContactUseCaseImpl implements SubmitContactUseCase {

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

    private final HCaptchaValidator captchaValidator;
    private final ContactRequestsRepo contactRepository;
    private final SendMailUseCase sendMailUseCase;  // Inject SendMailUseCase

    public SubmitContactUseCaseImpl(HCaptchaValidator captchaValidator,
                                    ContactRequestsRepo contactRepository,
                                    SendMailUseCase sendMailUseCase) {
        this.captchaValidator = captchaValidator;
        this.contactRepository = contactRepository;
        this.sendMailUseCase = sendMailUseCase;
    }

    @Override
    public ResponseEntity<String> submitContact(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);

        // Send notifications
        try {
            notifyContactAndTeam(request);
        } catch (Exception e) {
            log.error("Error sending email notifications: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error sending notifications");
        }

        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());

        // Send confirmation email to user
        MailRequest userMailRequest = new MailRequest();
        userMailRequest.setTo(request.email());
        userMailRequest.setSubject(userSubject);
        userMailRequest.setMessage(userBody);
        sendMailUseCase.execute(userMailRequest);

        // 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()
        );

        // Send team notification email
        MailRequest teamMailRequest = new MailRequest();
        teamMailRequest.setTo("rhein.software@gmail.com");
        teamMailRequest.setSubject(teamSubject);
        teamMailRequest.setMessage(teamBody);
        sendMailUseCase.execute(teamMailRequest);
    }

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