package de.oaa.xxx.registration;

import de.oaa.xxx.mail.Email;
import de.oaa.xxx.mail.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/registration")
public class RegistrationController {

    private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationController.class);

    private final RegistrationRepository registrationRepository;
    private final MailService mailService;

    public RegistrationController(RegistrationRepository registrationRepository, MailService mailService) {
        this.registrationRepository = registrationRepository;
        this.mailService = mailService;
    }

    @PostMapping
    public ResponseEntity<Void> create(@RequestBody Registration registration) {
        LOGGER.info("POST {}: {}", getClass().getName(), registration);
        if (!registrationRepository.findByEmail(registration.getEmail()).isEmpty()) {
            LOGGER.warn("User mit E-Mail {} bereits vorhanden", registration.getEmail());
            return ResponseEntity.badRequest().build();
        }
        RegistrationEntity entity = RegistrationEntity.create(registration);
        registrationRepository.save(entity);
        registration.setId(entity.getRegistrationId());

        Email email = new Email();
        email.setTitel("Bitte bestätige deine E-Mail Adresse");
        email.setEmailAdresse(registration.getEmail());
        email.setText(getMailText(registration));

        if (!mailService.send(email)) {
            registrationRepository.delete(entity);
            return ResponseEntity.internalServerError().build();
        }
        return ResponseEntity.accepted().build();
    }

    private String getMailText(Registration registration) {
        return """
                <html>
                <h1>Moin %s</h1>
                <p>Vielen Dank für deine Anmeldung bei XXX-BDSM Game!</p>
                <p>Klicke <a href="http://localhost:8080/registration/activation/%s">hier</a> um deine E-Mail-Adresse zu bestätigen.</p>
                <p>Und nun viel Spass beim Spiel!</p>
                </html>""".formatted(registration.getName(), registration.getId().toString());
    }
}
