// 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.vitess.controller;

import com.pingcap.dto.GitHubRepoDTO;
import com.pingcap.vitess.repository.GitHubReposMapper;
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;

/**
 * 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 {
        if (!reposMapper.selectRepoCountAndLock(repos).equals(0)) {
            throw new DuplicateKeyException("You need to check key duplicate, and you got it.");
        }

        reposMapper.insertByBatch(repos);
    }
}
