package ru.kayashov.bar.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import ru.kayashov.bar.controller.dto.cocktail.CocktailFilterRequestDto;
import ru.kayashov.bar.controller.dto.cocktail.CocktailForIngredientModalDto;
import ru.kayashov.bar.controller.dto.cocktail.CocktailForListResponseDto;
import ru.kayashov.bar.controller.dto.cocktail.CocktailModalDto;
import ru.kayashov.bar.controller.dto.cocktail.CocktailSimpleResponseDto;
import ru.kayashov.bar.controller.dto.cocktail.ReceiptResponseDto;
import ru.kayashov.bar.controller.dto.cocktail.SortingEnum;
import ru.kayashov.bar.controller.dto.ingredient.IngredientSimpleResponseDto;
import ru.kayashov.bar.mapper.CocktailMapper;
import ru.kayashov.bar.model.entity.Alcoholic;
import ru.kayashov.bar.model.entity.Category;
import ru.kayashov.bar.model.entity.CocktailEntity;
import ru.kayashov.bar.model.entity.Glass;
import ru.kayashov.bar.model.entity.IngredientEntity;
import ru.kayashov.bar.model.entity.ReceiptEntity;
import ru.kayashov.bar.repository.CocktailRepository;
import ru.kayashov.bar.repository.IngredientRepository;
import ru.kayashov.bar.repository.ReceiptRepository;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class CocktailService {

    private final CocktailRepository cocktailRepository;
    @Value("${cocktail.photo.path}")
    private String photoFolder;

    private final CocktailMapper mapper;

    private final CocktailRepository repository;
    private final ReceiptRepository receiptRepository;
    private final IngredientRepository ingredientRepository;
    private final VisitorService visitorService;

    private final EntityManager entityManager;

    /**
     * Вывод меню бара
     */
    @Transactional
    public List<CocktailForListResponseDto> getMenu(CocktailFilterRequestDto dto) {
        return mapper.cocktailsToDtoList(criteria(dto), dto.getAll(), false);
    }

    @Transactional
    public List<CocktailForListResponseDto> calc() {
        CocktailFilterRequestDto dto = new CocktailFilterRequestDto();
        dto.setPage(0);
        dto.setSize(1000);
        dto.setAll(false);
        dto.setOnlyFavourite(false);
        dto.setSort(SortingEnum.NAME_ASC);

        return mapper.cocktailsToDtoList(criteria(dto), false, true);
    }

    private List<CocktailEntity> criteria(CocktailFilterRequestDto dto) {
        Session session = entityManager.unwrap(Session.class);
        CriteriaBuilder cb = session.getCriteriaBuilder();
        CriteriaQuery<CocktailEntity> criteriaQuery = cb.createQuery(CocktailEntity.class);
        Root<CocktailEntity> root = criteriaQuery.from(CocktailEntity.class);
        List<Predicate> predicates = new ArrayList<>();

        criteriaQuery.distinct(true);
        if (!dto.getAll()) {
            Predicate pr = cb.isTrue(root.get("allowed"));
            predicates.add(pr);
        }

        if (!dto.getSearch().isEmpty()) {
            String[] search = dto.getSearch().split(" ");
            List<Predicate> in = new ArrayList<>();
            Join<CocktailEntity, ReceiptEntity> receiptJoin = root.join("receipt", JoinType.LEFT);
            for (String s : search) {
                in.add(cb.like(cb.lower(root.get("name")), "%" + s.toLowerCase() + "%"));
                in.add(cb.like(cb.lower(receiptJoin.get("ingredient").get("name")), "%" + s.toLowerCase() + "%"));
            }
            predicates.add(cb.or(in.toArray(new Predicate[0])));
        }

        if (dto.getOnlyFavourite()) {
            predicates.add(cb.isTrue(root.get("favourite")));
        }

        if (dto.getGlass() != null && !dto.getGlass().isEmpty()) {
            predicates.add(root.get("glass").in(dto.getGlass().stream().map(Glass::findValue).toList()));
        }

        if (dto.getCategory() != null && !dto.getCategory().isEmpty()) {
            predicates.add(root.get("category").in(dto.getCategory().stream().map(Category::findValue).toList()));
        }

        if (dto.getAlcohol() != null && !dto.getAlcohol().isEmpty()) {
            predicates.add(root.get("alcoholic").in(dto.getAlcohol().stream().map(Alcoholic::findValue).toList()));
        }

        //todo: доделать другие виды сортировки
        Order order;
        switch (dto.getSort()) {
            case NAME_ASC -> order = cb.asc(root.get("name"));
            case NAME_DESC -> order = cb.desc(root.get("name"));
            default -> order = cb.asc(root.get("name"));
        }

        criteriaQuery.where(predicates.toArray(new Predicate[0]))
                .orderBy(order);
        Query<CocktailEntity> query = session.createQuery(criteriaQuery);
        query.setFirstResult(dto.getPage() * dto.getSize());
        query.setMaxResults(dto.getSize());
        List<CocktailEntity> cocktailEntities = query.getResultList();

        log.info("Найдено {} коктейлей", cocktailEntities.size());
        return cocktailEntities;
    }

    public CocktailForListResponseDto findById(Long id) {
        CocktailEntity cocktail = repository.findById(id).orElseThrow();
        return mapper.cocktailToFullDto(cocktail);
    }

    @Transactional
    public void edit(CocktailForListResponseDto dto) {
        CocktailEntity cocktail;
        if (dto.getId() == null) {
            if (dto.getName() == null) {
                throw new RuntimeException("Коктейль не может быть без названия");
            }
            cocktail = new CocktailEntity();
            cocktail.setReceipt(new ArrayList<>());
        } else {
            cocktail = repository.findById(dto.getId())
                    .orElseThrow(() -> new RuntimeException("Не удалось найти коктейль с id " + dto.getId()));
        }

        boolean allowed = dto.getReceipt().stream()
                .map(ReceiptResponseDto::getIngredient)
                .allMatch(IngredientSimpleResponseDto::getIsHave);

        cocktail.setAllowed(allowed);
        cocktail.setName(dto.getName());
        cocktail.setInstructions(dto.getInstructions());
        cocktail.setImage(dto.getImage());
        cocktail.setVideo(cocktail.getVideo());
        cocktail.setCategory(Category.findValue(dto.getCategory()));
        cocktail.setGlass(Glass.findValue(dto.getGlass()));
        cocktail.setAlcoholic(Alcoholic.findValue(dto.getAlcoholic()));
        cocktail.setRating(cocktail.getRating());
        cocktail = repository.save(cocktail);

        log.info("{} коктейль {}", dto.getId() == null ? "Создан" : "Изменен", cocktail.getName());

        editCocktailReceipts(cocktail.getReceipt(), dto.getReceipt(), cocktail);
    }

    public void editFavourite(Long cocktailId, boolean put) {
        log.info("Коктейль с id {} {}", cocktailId, put ? "добавлен в избранное" : "удален из избранного");
        cocktailRepository.updateFavouriteById(cocktailId, put);
    }

    public void setRating(Long cocktailId, Integer rating) {
        log.info("Коктейлю с id {} выставлена новая оценка {}", cocktailId, rating);
        cocktailRepository.updateRatingById(cocktailId, rating);
    }

    public CocktailModalDto getForModal(Long id) {
        CocktailEntity cocktail = repository.findById(id).orElseThrow(RuntimeException::new);
        return mapper.cocktailToModalDto(cocktail);
    }

    public List<CocktailSimpleResponseDto> getSimple() {
        return repository.findAll().stream()
                .map(CocktailSimpleResponseDto::mapToDto)
                .toList();
    }

    public String savePhoto(MultipartFile file) throws IOException {
        File folder = new File(photoFolder);
        List<File> files = Arrays.asList(Objects.requireNonNull(folder.listFiles()));
        String fileName = getPhotoPath(files, file.getOriginalFilename());
        String fullName = photoFolder + "/" + fileName;
        file.transferTo(new File(fullName));
        log.info("сохранено фото {}", fileName);
        return "/assets/cocktails/" + fileName;
    }

    public void delete(Long id) {
        CocktailEntity cocktail = repository.findById(id).orElseThrow(RuntimeException::new);
        log.info("Удален коктейль {}", cocktail);
        repository.delete(cocktail);
    }

    public String findInstructions(Long id) {
        CocktailEntity cocktail = repository.findById(id).orElseThrow(RuntimeException::new);
        return cocktail.getInstructions();
    }

    public List<CocktailForIngredientModalDto> findByIngredient(Long id) {
        return ingredientRepository.findById(id).orElseThrow(RuntimeException::new)
                .getReceipts()
                .stream()
                .map(ReceiptEntity::getCocktail)
                .distinct()
                .map(mapper::cocktailToIngredientDtoList)
                .toList();
    }

    //todo: попробовать отыграть эту связку каскадами
    private void editCocktailReceipts(List<ReceiptEntity> old, List<ReceiptResponseDto> actual, CocktailEntity cocktail) {
        for (ReceiptResponseDto receipt : actual) {
            if (receipt.getId() == null) {
                createNewReceipt(receipt, cocktail);
                continue;
            }
            old.stream().filter(r -> receipt.getId().equals(r.getId()))
                    .findFirst()
                    .ifPresent(r -> equalReceipt(r, receipt));

            old.removeIf(r -> r.getId().equals(receipt.getId()));
        }

        old.forEach(r -> receiptRepository.deleteById(r.getId()));
    }

    private void equalReceipt(ReceiptEntity old, ReceiptResponseDto actual) {
        boolean needSave = false;
        if (!actual.getIngredient().getId().equals(old.getIngredient().getId())) {
            IngredientEntity ingredient = ingredientRepository.findById(actual.getIngredient().getId()).orElseThrow();
            old.setIngredient(ingredient);
            needSave = true;
        }
        if (old.getUnit() == null || actual.getUnit() == null ||
                !Objects.equals(old.getUnit().getId(), actual.getUnit().getId())) {
            old.setUnit(actual.getUnit());
            needSave = true;
        }
        if (!Objects.equals(old.getCount(), actual.getCount())) {
            old.setCount(actual.getCount());
            needSave = true;
        }
        if (needSave) {
            receiptRepository.save(old);
        }
    }

    private void createNewReceipt(ReceiptResponseDto receipt, CocktailEntity cocktail) {
        ReceiptEntity receiptEntity = new ReceiptEntity();
        IngredientEntity ingredient = ingredientRepository.findById(receipt.getIngredient().getId()).orElseThrow();
        receiptEntity.setIngredient(ingredient);
        receiptEntity.setCount(receipt.getCount());
        receiptEntity.setUnit(receipt.getUnit());
        receiptEntity.setCocktail(cocktail);
        receiptRepository.save(receiptEntity);
    }

    private String getPhotoPath(List<File> files, String originalName) {
        if (files.stream().map(File::getName).anyMatch(name -> name.equals(originalName))) {
            String[] split = originalName.split("\\.");
            String name = concatName(split) + "_c." + split[split.length - 1];
            return getPhotoPath(files, name);
        }
        return originalName;
    }

    private String concatName(String[] name) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < name.length - 1; i++) {
            sb.append(name[i]);
        }
        return sb.toString();
    }
}
