package marketing.heyday.hartmann.fotodocumentation.rest;

import static marketing.heyday.hartmann.fotodocumentation.rest.jackson.ApplicationConfigApi.JSON_OUT;

import java.util.Optional;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wildfly.security.auth.server.SecurityIdentity;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.annotation.security.PermitAll;
import jakarta.ejb.EJB;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import marketing.heyday.hartmann.fotodocumentation.core.service.LoginService;
import marketing.heyday.hartmann.fotodocumentation.core.utils.LoginUtils;
import marketing.heyday.hartmann.fotodocumentation.rest.vo.TokenPairValue;

/**
 * 
 * <p>Copyright: Copyright (c) 2024</p>
 * <p>Company: heyday Marketing GmbH</p>
 * @author <a href="mailto:p.verboom@heyday.marketing">Patrick Verboom</a>
 * @version 1.0
 * 
 * created: 21 Jan 2026
 */

@RequestScoped
@Path("login")
@PermitAll
public class LoginResource {
	private static final Log LOG = LogFactory.getLog(LoginResource.class);

	@EJB
	private LoginService loginService;

	@Inject
	private LoginUtils loginUtils;

	@GET
	@Path("/")
	@Produces(JSON_OUT)
	@Operation(summary = "Get logged in user")
	@ApiResponse(responseCode = "200", description = "Successfully retrieved logged in user", content = @Content(mediaType = JSON_OUT, schema = @Schema(implementation = TokenPairValue.class)))
	@ApiResponse(responseCode = "500", description = "Internal server error")
	public Response doLogin(@Context HttpServletRequest httpServletRequest) {
		Optional<SecurityIdentity> identity = loginUtils.authenticate(httpServletRequest);
		if (identity.isEmpty()) {
			LOG.debug("identity empty login invalid");
			return Response.status(Status.UNAUTHORIZED).build();
		}
		String username = identity.get().getPrincipal().getName();

		LOG.debug("Login valid returning jwt");
		String deviceInfo = loginUtils.extractDeviceInfo(httpServletRequest);
		String ipAddress = loginUtils.extractIpAddress(httpServletRequest);

		var tokenPairValue = loginService.authenticateUser(username, deviceInfo, ipAddress);
		return Response.ok(tokenPairValue).build();
	}
}
