package com.alttd.altitudeweb.controllers.data_from_auth;

import com.nimbusds.jwt.JWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.Optional;
import java.util.UUID;

@Slf4j
@Service
public class AuthenticatedUuid {
    @Value("${UNSECURED:#{false}}")
    private boolean unsecured;

    /**
     * Extracts and validates the authenticated user's UUID from the JWT token.
     *
     * @return The UUID of the authenticated user
     * @throws ResponseStatusException with 401 status if authentication is invalid
     */
    public UUID getAuthenticatedUserUuid() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null || !(authentication.getPrincipal() instanceof Jwt jwt)) {
            log.error("Authentication principal is null {} or not a JWT {}",
                      authentication == null, authentication == null ?
                                              "null" : authentication.getPrincipal() instanceof JWT);
            if (unsecured) {
                return UUID.fromString("55e46bc3-2a29-4c53-850f-dbd944dc5c5f");
            }
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Authentication required");
        }

        String stringUuid = jwt.getSubject();

        try {
            return UUID.fromString(stringUuid);
        } catch (IllegalArgumentException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid UUID format");
        }
    }

    /**
     * Extracts the authenticated user's UUID from the JWT token.
     *
     * @return The UUID of the authenticated user
     */
    public Optional<UUID> tryGetAuthenticatedUserUuid() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null || !(authentication.getPrincipal() instanceof Jwt jwt)) {
            if (unsecured) {
                return Optional.of(UUID.fromString("55e46bc3-2a29-4c53-850f-dbd944dc5c5f"));
            }
            return Optional.empty();
        }

        String stringUuid = jwt.getSubject();

        try {
            return Optional.of(UUID.fromString(stringUuid));
        } catch (IllegalArgumentException e) {
            return Optional.empty();
        }
    }
}
