package com.kospo.talk.service.impl;

import com.kospo.talk.model.*;
import com.kospo.talk.payload.QuestionDto;
import com.kospo.talk.repository.QuestionRepository;
import com.kospo.talk.repository.SmUserRepository;
import com.kospo.talk.service.QuestionService;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class QuestionServiceImpl implements QuestionService {
    private final QuestionRepository questionRepository;
    private final SmUserRepository smUserRepository;

    @Transactional
    @Override
    public List<Question> findBySabun(String sabun) {
        return questionRepository.findBySabun(sabun);
    }

    @Override
    @Transactional
    public List<Question> findByWorkId(String workId) {
        return questionRepository.findByIdWorkIdOrderByIdSortAsc(workId);
    }

    @Override
    public Question findByWorkIdAndContent(String workId, String content) {
        return questionRepository.findByIdWorkIdAndContentLike(workId, content);
    }
    
    @Override
    public void save(QuestionDto questionDto) {
        questionRepository.save(Question.to(questionDto));
    }
    
    @Override
    public void update(QuestionDto questionDto) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Question question = Question.to(questionDto);
        Question oriQuestion = questionRepository.findById(question.getId()).get();
        SmUser smUser = smUserRepository.findById(SmUserId.builder().sabun(user.getSabun()).workId(oriQuestion.getId().getWorkId()).build()).get();
        if(smUser != null) {
            if(question.getId().getSort() != oriQuestion.getId().getSort()) {
                questionRepository.delete(question);

                oriQuestion.setId(question.getId());
            }
            oriQuestion.setContent(question.getContent());
            oriQuestion.setAsk(question.getAsk());
            questionRepository.save(oriQuestion);
        }
    }
    
    @Override
    public void delete(QuestionId questionId) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Question oriQuestion = questionRepository.findById(questionId).get();
        SmUser smUser = smUserRepository.findById(SmUserId.builder().sabun(user.getSabun()).workId(oriQuestion.getId().getWorkId()).build()).get();
         if(smUser != null) {
            questionRepository.delete(oriQuestion);
        }
    }
}
