package com.eactive.httpmockserver.user.service;

import com.eactive.httpmockserver.common.entity.EnabledStatus;
import com.eactive.httpmockserver.common.exception.UserNotFoundException;
import com.eactive.httpmockserver.user.entity.StaffUser;
import com.eactive.httpmockserver.user.entity.UserStatus;
import com.eactive.httpmockserver.user.repository.StaffUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

import static com.eactive.httpmockserver.user.service.UserService.USER_NOT_FOUND_MESSAGE;

@Service
@Transactional
public class StaffUserService {

    @Autowired
    private StaffUserRepository staffUserRepository;

    public Page<StaffUser> findAll(Specification<StaffUser> spec, Pageable pageable) {
        return staffUserRepository.findAll(spec, pageable);
    }

    public StaffUser findById(String id) {
        return staffUserRepository.findById(id).orElseThrow(() -> new UserNotFoundException(USER_NOT_FOUND_MESSAGE));
    }

    public void update(String esntlId, StaffUser user) {
        StaffUser original = staffUserRepository.findById(esntlId).orElseThrow(() -> new UserNotFoundException(USER_NOT_FOUND_MESSAGE));
        original.setUserId(user.getUserId());
        original.setMobilePhone(user.getMobilePhone());
        original.setStatus(user.getStatus());
        original.setLockAt(user.getLockAt());
        if (original.getLockAt().equals(EnabledStatus.N)) {
            original.setLockCnt(0);
            original.setLastLockDate(null);
        }

        original.setUserSecurity(user.getUserSecurity());
        staffUserRepository.save(original);
    }

    public void deleteById(String esntlId) {
        StaffUser user = staffUserRepository.findById(esntlId).orElseThrow(() -> new UserNotFoundException(USER_NOT_FOUND_MESSAGE));
        user.setUserId(UserStatus.DELETED.toString());
        user.setUsername(UserStatus.DELETED.toString());
        user.setStatus(UserStatus.DELETED);
        user.setLockAt(EnabledStatus.Y);
        staffUserRepository.save(user);
    }

    public void create(StaffUser user) {
        user.setEsntlId(UUID.randomUUID().toString());
        user.setStatus(UserStatus.ACTIVE);
        user.setLockAt(EnabledStatus.N);
        user.setLockCnt(0);

        staffUserRepository.save(user);



    }
}
