package com.its.op.service.its;

import com.its.op.dao.repository.its.oper.TbUserCnncHsRepository;
import com.its.op.dao.repository.its.oper.TbUserInfrRepository;
import com.its.op.dto.its.LoginDto;
import com.its.op.entity.its.oper.TbUserCnncHs;
import com.its.op.entity.its.oper.TbUserInfr;
import com.its.utils.ItsUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Service
public class LoginService {

    private final TbUserInfrRepository userRepo;
    private final TbUserCnncHsRepository cnncHsRepo;

    /**
     * 로그인 처리
     * @param req
     * @return
     */
    public LoginDto login(LoginDto.LoginReqDto req) {

        LoginDto result = LoginDto.builder()
                .userId(req.getUsername())
                .loginHms(ItsUtils.getSysTime())
                .build();

        Optional<TbUserInfr> userInfr = this.userRepo.findById(req.getUsername());
        if (userInfr.isPresent()) {
            // found
            result.setLoginResult("success");

            TbUserCnncHs cnncHs = req.toCnnsHsEntity();
            this.cnncHsRepo.save(cnncHs);
        }
        else {
            // not found
            result.setLoginResult("fail");
        }

        return result;
    }

    /**
     * 로그아웃 처리
     * @param req
     */
    public void logout(LoginDto.LogoutReqDto req) {

        TbUserCnncHs cnncHs = req.toCnncHsEntity();
        cnncHsRepo.updateData(cnncHs.getLoginHms(), cnncHs.getUserId(), cnncHs.getLogoutHms());
        //this.cnncHsRepo.save(cnncHs);
    }

    /**
     * 사용자 ID 로 조회
     * @param userId
     * @return
     */
    public LoginDto findById(String userId) {

        LoginDto result = LoginDto.builder()
                .userId(userId)
                .loginHms(ItsUtils.getSysTime())
                .build();

        Optional<TbUserInfr> userInfr = this.userRepo.findById(userId);
        if (userInfr.isPresent()) {
            result.setPassword(userInfr.get().getPwd());
            result.setLoginResult("success");
        }
        else {
            result.setLoginResult("fail");
        }

        return result;
    }

}
