package ru.yandex.direct.web.entity.user.service;

import java.util.Optional;

import javax.annotation.ParametersAreNonnullByDefault;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import ru.yandex.direct.core.entity.user.model.User;
import ru.yandex.direct.core.entity.user.service.UserService;
import ru.yandex.direct.core.security.DirectAuthentication;
import ru.yandex.direct.web.core.model.WebErrorResponse;
import ru.yandex.direct.web.core.model.WebResponse;
import ru.yandex.direct.web.entity.user.model.OfferAcceptedResponse;
import ru.yandex.direct.web.entity.user.model.UserLoginResponse;

import static ru.yandex.direct.utils.CommonUtils.notEquals;

@Service
@ParametersAreNonnullByDefault
public class WebUserService {

    private final UserService userService;

    @Autowired
    public WebUserService(UserService userService) {
        this.userService = userService;
    }

    public WebResponse setOfferAccepted(DirectAuthentication auth) {
        Long operatorId = Optional.ofNullable(auth.getOperator())
                .map(User::getId)
                .orElse(null);
        Long subjectUserId = Optional.ofNullable(auth.getSubjectUser())
                .map(User::getId)
                .orElse(null);
        if (subjectUserId == null) {
            return new WebErrorResponse(404, "User not found.");
        }
        if (notEquals(operatorId, subjectUserId)) {
            return new WebErrorResponse(403, "The offer must be accepted personally by the representative.");
        }
        userService.setOfferAccepted(subjectUserId);
        return new OfferAcceptedResponse();
    }

    public WebResponse getLogin(DirectAuthentication auth) {
        return Optional.ofNullable(auth.getSubjectUser())
                .map(user -> (WebResponse) new UserLoginResponse(user.getLogin()))
                .orElse(new WebErrorResponse(HttpStatus.NOT_FOUND.value(), HttpStatus.NOT_FOUND.toString()));
    }
}
