package com.bytesw.bytebot.etl.jdbc;

import com.bytesw.bytebot.etl.beans.SessionBean;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;

@Component
public class ETLSessionBotJDBCRepository {

    @Autowired
    @Qualifier("sqlSessionFactory")
    private SqlSessionFactory sqlSessionFactory;

    public SessionBean getLastSessionByUser(Long userId) {
        SqlSession session = sqlSessionFactory.openSession();

        try {
            Map<String, Object> params = new HashMap<>();
            params.put("userId", userId);
            return session.selectOne("com.bytesw.bytebot.dao.jdbc.ETLSessionMapper.getLastSessionByUser", params);
        } finally {
            session.close();
        }
    }

    public void updateLastEventDate(Long sessionID, OffsetDateTime lastEventDate) {
        SqlSession session = sqlSessionFactory.openSession();

        try {
            Map<String, Object> params = new HashMap<>();
            params.put("sessionId", sessionID);
            params.put("lastEventDate", lastEventDate);
            session.update("com.bytesw.bytebot.dao.jdbc.ETLSessionMapper.updateLastEventDate", params);
        } finally {
            session.close();
        }
    }
}
