package com.ctsb.my_product_management_svc.category;

import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.List;

@Service
@AllArgsConstructor
public class CategoryService {

    private final CategoryRepository categoryRepository;
    private static final String NOT_FOUND = "Category with %s id is not found!";

    public List <Category> findAll(){
        return categoryRepository.findAll();
    }

    public Category findById(Long id){
        return categoryRepository.findById(id).orElseThrow(
                () -> new ResponseStatusException(HttpStatus.NOT_FOUND, String.format(NOT_FOUND,id))
        );
    }

    public Category create(CategoryDto categoryDto){
        Category category = mapper(categoryDto);
        category.setCreatedAt(LocalDateTime.now());
        category.setUpdatedAt(null);
        return categoryRepository.save(category);
    }

    public Category update(Long id, CategoryDto categoryDto){
        Category existingCategory = categoryRepository.findById(id).orElseThrow(
                () -> new ResponseStatusException(HttpStatus.NOT_FOUND, String.format(NOT_FOUND,id))
        );
        if(categoryDto.name() != null){
            existingCategory.setName(categoryDto.name());
        }
        if(categoryDto.description() != null){
            existingCategory.setDescription(categoryDto.description());
        }
        if(categoryDto.active() != null){
            existingCategory.setActive(categoryDto.active());
        }
        existingCategory.setUpdatedAt(LocalDateTime.now());
        return categoryRepository.save(existingCategory);
    }

    public void delete(Long id){
        Category category = categoryRepository.findById(id).orElseThrow(
                () -> new ResponseStatusException(HttpStatus.NOT_FOUND, String.format(NOT_FOUND,id))
        );
        categoryRepository.deleteById(id);
    }

    private Category mapper(CategoryDto categoryDto){
        var category = new Category();
        category.setName(categoryDto.name());
        category.setDescription(categoryDto.description());
        category.setActive(categoryDto.active());
        return category;
    }
}
