package de.oaa.xxx.registration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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;

import de.oaa.xxx.mail.Email;
import de.oaa.xxx.mail.MailService;
import de.oaa.xxx.user.UserRepository;

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

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

    @Value("${app.base-url:http://localhost:8080}")
    private String baseUrl;

    private final RegistrationRepository registrationRepository;
    private final UserRepository userRepository;
    private final MailService mailService;

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

    @PostMapping
    public ResponseEntity<String> create(@RequestBody Registration registration) {
        LOGGER.info("POST {}: {}", getClass().getName(), registration);
        if (registrationRepository.findByEmail(registration.getEmail()).isPresent()
                || userRepository.findByEmail(registration.getEmail()).isPresent()) {
            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.status(202).build();
    }

    private String getMailText(Registration registration) {
        String uuid = registration.getId().toString();
        return """
                <html>
                <h1>Moin %s</h1>
                <p>Vielen Dank für deine Anmeldung bei XXX-BDSM Game!</p>
                <p>Klicke <a href="%s/activation/%s">hier</a> um deine E-Mail-Adresse zu bestätigen.</p>
                <hr style="margin:1.5rem 0; border:none; border-top:1px solid #ddd;">
                <p style="color:#666; font-size:0.9em;">
                    Falls der Link nicht funktioniert, kannst du deine E-Mail-Adresse auch manuell bestätigen.<br>
                    Öffne dazu <a href="%s/activate.html">%s/activate.html</a> und gib folgenden Code ein:
                </p>
                <p style="font-family:monospace; font-size:1.1em; background:#f4f4f4; padding:0.5rem 1rem; border-radius:4px; display:inline-block;">%s</p>
                <p>Viel Spaß beim Spiel!</p>
                </html>""".formatted(registration.getName(), baseUrl, uuid, baseUrl, baseUrl, uuid);
    }
}
