package com.yaoyuan.jiscuss.service.impl;

import com.yaoyuan.jiscuss.entity.Discussion;
import com.yaoyuan.jiscuss.repository.DiscussionsRepository;
import com.yaoyuan.jiscuss.repository.UsersRepository;
import com.yaoyuan.jiscuss.service.IDiscussionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DiscussionsServiceImpl implements IDiscussionsService {

    @Autowired
    private DiscussionsRepository discussionsRepository;

    @Autowired
    private UsersRepository usersRepository;

    @Transactional(readOnly = true)
    @Override
    public List<Discussion> getAllList() {
        return discussionsRepository.findAll();
    }

    @Transactional
    @Override
    public Discussion insert(Discussion discussion) {
        Discussion saved = discussionsRepository.save(discussion);
        // Maintain user discussions count
        if (discussion.getCreateId() != null) {
            usersRepository.incrementDiscussionCount(discussion.getCreateId());
        }
        return saved;
    }

    @Transactional(readOnly = true)
    @Override
    public Discussion findOne(Integer id) {
        return discussionsRepository.findById(id).orElse(null);
    }

    @Transactional(readOnly = true)
    @Override
    public Page<Discussion> queryAllDiscussionsList(Discussion discussion, int pageNum, int pageSize, String tag, String type) {
        Sort sort = switch (type) {
            case "hot" -> Sort.by(Sort.Direction.DESC, "likeCount");
            case "new" -> Sort.by(Sort.Direction.DESC, "startTime");
            default    -> Sort.by(Sort.Direction.DESC, "id");
        };
        Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
        Example<Discussion> example = Example.of(discussion);
        if (tag != null && !"all".equals(tag)) {
            return discussionsRepository.findByQuery(tag, pageable);
        } else {
            return discussionsRepository.findAll(example, pageable);
        }
    }

    @Transactional
    @Override
    public void incrementViewCount(Integer id) {
        discussionsRepository.incrementViewCount(id);
    }
}
