package skilldesk.mapper;

import jakarta.inject.Singleton;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import skilldesk.entity.Message;

import java.util.List;

@Singleton
public class MessageRepository {

    private final SqlSessionFactory sqlSessionFactory;

    public MessageRepository(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    public Message findFirst() {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            return session.getMapper(MessageMapper.class).findFirst();
        }
    }

    public List<Message> findAll() {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            return session.getMapper(MessageMapper.class).findAll();
        }
    }

    public void insert(Message message) {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            session.getMapper(MessageMapper.class).insert(message);
        }
    }

    public int update(Integer id, String content) {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            return session.getMapper(MessageMapper.class).update(id, content);
        }
    }

    public int deleteById(Integer id) {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            return session.getMapper(MessageMapper.class).deleteById(id);
        }
    }
}
