package com.example.system.service.impl;

import com.example.system.mapper.CompetitionMapper;
import com.example.system.mapper.UserMapper;
import com.example.system.model.CompetitionTable;
import com.example.system.model.ResultCompetitionTable;
import com.example.system.repository.CompetitionRepository;
import com.example.system.service.CompetitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CompetitionServiceImpl implements CompetitionService {
    private final CompetitionRepository competitionRepository;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CompetitionMapper competitionMapper;

    @Autowired
    public CompetitionServiceImpl(CompetitionRepository competitionRepository) {
        this.competitionRepository = competitionRepository;
    }

    @Override
    public CompetitionTable addCompetition(CompetitionTable competition) {
        // 添加竞赛信息，此处可加入额外业务逻辑
        return competitionRepository.save(competition);
    }

    @Override
    public boolean deleteCompetition(Long id) {
        // 尝试删除竞赛信息，如果竞赛信息不存在，则捕获异常并返回false
        try {
            competitionRepository.deleteById(id);
            return true;
        } catch (EmptyResultDataAccessException e) {
            // 如果没有找到要删除的记录，返回false
            return false;
        }
    }

    @Override
    public CompetitionTable updateCompetition(CompetitionTable competition) {
        // 更新竞赛信息，此处可加入额外业务逻辑
        return competitionRepository.save(competition);
    }

    @Override
    public Optional<CompetitionTable> getCompetitionById(Long id) {
        // 根据ID获取竞赛信息
        return competitionRepository.findById(id);
    }

    @Override
    public List<ResultCompetitionTable> getAllCompetitions() {
        // 获取所有竞赛信息
        List<ResultCompetitionTable> competitionTables = competitionMapper.getCompetition();
        for (ResultCompetitionTable competitionTable : competitionTables) {
            String userName = userMapper.getNameById(competitionTable.getUserId());
            competitionTable.setUserName(userName);

        }
        return competitionTables;
    }

    @Override
    public List<CompetitionTable> searchCompetitionsByName(String searchTerm) {
        return competitionRepository.findByCompetitionNameContaining(searchTerm);
    }
}