package com.its.api.its.service;

import com.its.api.its.model.dto.LoginDto;
import com.its.api.its.model.entity.oper.TbUserCnncHs;
import com.its.api.its.model.entity.oper.TbUserInfr;
import com.its.api.its.repository.oper.TbUserCnncHsRepository;
import com.its.api.its.repository.oper.TbUserInfrRepository;
import com.its.api.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.getUserId())
                .loginHms(ItsUtils.getSysTime())
                .build();

        Optional<TbUserInfr> userInfr = this.userRepo.findById(req.getUserId());
        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.toCnnsHsEntity();
        this.cnncHsRepo.save(cnncHs);
    }
}
