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

import kr.co.accura.wbx.spring.common.NotFoundException;
import kr.co.accura.wtm.domain.config.dto.OverheadTypeDto;
import kr.co.accura.wtm.domain.config.entity.OverheadType;
import kr.co.accura.wtm.domain.config.repository.OverheadTypeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@RequiredArgsConstructor
public class OverheadTypeService {

    private final OverheadTypeRepository repository;

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

    public OverheadTypeDto create(OverheadTypeDto dto) {
        OverheadType entity = OverheadType.builder()
                .code(dto.code())
                .name(dto.name())
                .category(dto.category())
                .isActive(dto.isActive() != null ? dto.isActive() : true)
                .sortOrder(dto.sortOrder() != null ? dto.sortOrder() : 0)
                .build();
        return toDto(repository.save(entity));
    }

    public OverheadTypeDto update(Long id, OverheadTypeDto dto) {
        OverheadType entity = repository.findById(id)
                .orElseThrow(() -> new NotFoundException("Overhead type not found: " + id));
        entity.setCode(dto.code());
        entity.setName(dto.name());
        entity.setCategory(dto.category());
        if (dto.isActive() != null) entity.setIsActive(dto.isActive());
        if (dto.sortOrder() != null) entity.setSortOrder(dto.sortOrder());
        return toDto(repository.save(entity));
    }

    private OverheadTypeDto toDto(OverheadType e) {
        return new OverheadTypeDto(e.getId(), e.getCode(), e.getName(),
                e.getCategory(), e.getIsActive(), e.getSortOrder());
    }
}
