package kr.co.accura.wtm.domain.config.service;

import kr.co.accura.wtm.domain.config.dto.WorkRuleDto;
import kr.co.accura.wtm.domain.config.entity.WorkRule;
import kr.co.accura.wtm.domain.config.repository.WorkRuleRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@RequiredArgsConstructor
public class WorkRuleService {

    private final WorkRuleRepository repository;

    @Transactional(readOnly = true)
    public List<WorkRuleDto> getAll() {
        return repository.findByIsActiveTrue().stream()
                .map(this::toDto)
                .toList();
    }

    public List<WorkRuleDto> saveAll(List<WorkRuleDto> dtos) {
        List<WorkRule> rules = dtos.stream().map(dto -> {
            WorkRule rule;
            if (dto.id() != null) {
                rule = repository.findById(dto.id()).orElse(new WorkRule());
            } else if (dto.location() != null) {
                rule = repository.findByLocation(dto.location()).orElse(new WorkRule());
            } else {
                rule = new WorkRule();
            }
            rule.setLocation(dto.location());
            if (dto.minDailyHours() != null) rule.setMinDailyHours(dto.minDailyHours());
            if (dto.maxDailyHours() != null) rule.setMaxDailyHours(dto.maxDailyHours());
            if (dto.maxWeeklyHours() != null) rule.setMaxWeeklyHours(dto.maxWeeklyHours());
            if (dto.isActive() != null) rule.setIsActive(dto.isActive());
            return rule;
        }).toList();

        return repository.saveAll(rules).stream()
                .map(this::toDto)
                .toList();
    }

    private WorkRuleDto toDto(WorkRule e) {
        return new WorkRuleDto(e.getId(), e.getLocation(),
                e.getMinDailyHours(), e.getMaxDailyHours(),
                e.getMaxWeeklyHours(), e.getIsActive());
    }
}
