package de.oaa.xxx.registration;

import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

@Path("registration")
@ApplicationScoped
public class RegistrationResource {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationResource.class);
	
	@Inject private RegistrationDAO dao;
	
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response create(Registration registration) {
		LOGGER.info("POST " + getClass().getName() + ": " + registration);
		if (dao.findByEmail(registration.getEmail()).size() > 0) {
			LOGGER.warn("User mit E-Mail " + registration.getEmail() + " bereits vorhanden");
			return Response.status(400).build();
		}
		RegistrationEntity entity = RegistrationEntity.create(registration);
		dao.persist(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 (!sendEmail(email)) {
			dao.remove(entity);
			return Response.serverError().build();
		}
		return Response.accepted().build();
	}
	
	private boolean sendEmail(Email email) {
		boolean result = false; 
		Client client = null;
		try {
			client = ClientBuilder.newClient();
			Response response = client.target("http://localhost:8080/mail-service/send").request().post(Entity.entity(email, MediaType.APPLICATION_JSON));
			if (200 == response.getStatus()) {
				result = true;
			} else {				
				LOGGER.error("E-Mail konnte nicht erzeugt werden...Status: {}", response.getStatus());
			}
		} finally {
			if (client != null) {
				client.close();
			}
		}
		return result;
	}
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Response get(@QueryParam("id") UUID id) {
		RegistrationEntity entity = dao.findById(id);
		if (entity != null) {
			return Response.ok(entity.toRegistration()).build();
		} else {
			return Response.noContent().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-service/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());
	}
			
}