// Copyright 2022 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.pingcap.baresharding.controller;

import com.pingcap.baresharding.repository.GitHubReposMapper;
import com.pingcap.dto.GitHubRepoDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * EventController
 *
 * @author Icemap
 * @date 2022/11/30
 */
@RequestMapping("/repo")
@RestController
public class RepoController {
    private static final Logger LOG = LoggerFactory.getLogger(RepoController.class);

    @Autowired
    GitHubReposMapper reposMapper;

    @PostMapping
    public boolean insertRepo(@RequestBody List<GitHubRepoDTO> repos) {
        try {
            checkAndInsert(repos);
        } catch (DuplicateKeyException e) {
            LOG.info(e.getMessage());
            return false;
        }

        return true;
    }

    @Transactional
    public void checkAndInsert(List<GitHubRepoDTO> repos) throws DuplicateKeyException {
        for (int shardID = 0; shardID < GitHubReposMapper.SHARD_NUMBER; shardID++) {
            if (!reposMapper.selectRepoCountAndLock(shardID, repos).equals(0)) {
                throw new DuplicateKeyException("You need to check key duplicate, and you got it.");
            }
        }

        for (int shardID = 0; shardID < GitHubReposMapper.SHARD_NUMBER; shardID++) {
            final int finalShardID = shardID;
            List<GitHubRepoDTO> shardRepoList = repos.stream()
                    .filter(repo -> repo.repoID() % GitHubReposMapper.SHARD_NUMBER == finalShardID)
                    .toList();
            if (!shardRepoList.isEmpty()) {
                reposMapper.insertByBatch(shardID, shardRepoList);
            }
        }
    }
}
