package de.avatic.lcc.repositories.users;

import de.avatic.lcc.model.db.users.Group;
import de.avatic.lcc.repositories.pagination.SearchQueryPagination;
import de.avatic.lcc.repositories.pagination.SearchQueryResult;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

@Repository
public class GroupRepository {
    private final JdbcTemplate jdbcTemplate;

    public GroupRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Transactional
    public SearchQueryResult<Group> listGroups(SearchQueryPagination pagination) {

        String query = "SELECT * FROM sys_group ORDER BY group_name LIMIT ? OFFSET ?";

        var groups = jdbcTemplate.query(query, new GroupMapper(),
                pagination.getLimit(), pagination.getOffset());

        Integer totalCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_group ORDER BY group_name",
                Integer.class
        );

        return new SearchQueryResult<>(groups, pagination.getPage(), totalCount, pagination.getLimit());
        
    }

    @Transactional
    public List<Integer> findGroupIds(List<String> groups) {
        if (groups == null || groups.isEmpty()) {
            return List.of();
        }

        // Create placeholders for parameterized query
        String placeholders = String.join(",", Collections.nCopies(groups.size(), "?"));
        String query = "SELECT id FROM sys_group WHERE group_name IN (" + placeholders + ")";


        return jdbcTemplate.query(
                query,
                ps -> {
                    for (int parameterIndex = 0; parameterIndex < groups.size(); parameterIndex++) {
                        ps.setString(parameterIndex + 1, groups.get(parameterIndex));
                    }
                },
                (rs, rowNum) -> rs.getInt("id")
        );

    }

    @Transactional
    public void updateGroup(Group group) {
        String query = "INSERT INTO sys_group (group_name, group_description) VALUES (?, ?) ON DUPLICATE KEY UPDATE group_description = ?";
        jdbcTemplate.update(query, group.getName(), group.getDescription(), group.getDescription());
    }

    private static class GroupMapper implements RowMapper<Group> {

        @Override
        public Group mapRow(ResultSet rs, int rowNum) throws SQLException {
            var group = new Group();

            group.setId(rs.getInt("id"));
            group.setName(rs.getString("group_name"));
            group.setDescription(rs.getString("group_description"));

            return group;
        }
    }
}
