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.mapper.CocktailMapper;
import ru.kayashov.bar.model.entity.Alcoholic;
import ru.kayashov.bar.model.entity.BarIngredientStorage;
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.model.entity.Visitor;
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 javax.persistence.criteria.Subquery;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@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());
    }

    private List<CocktailEntity> criteria(CocktailFilterRequestDto dto) {
        Visitor visitor = visitorService.getCurrentVisitor();

        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()) {
//            Long barId = visitor.getResidents().stream()
//                    .filter(BarResident::getActive)
//                    .map(BarResident::getBar)
//                    .map(BarEntity::getId)
//                    .toList()
//                    .get(0);
            Long barId = 1L;
            List<Long> cocktailIds = getAllowedCocktailIds(barId);
            Predicate pr = root.get("id").in(cocktailIds);
            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("glassEntity").get("name").in(dto.getGlass()));
        }

        if (dto.getCategory() != null && !dto.getCategory().isEmpty()) {
            predicates.add(root.get("categoryEntity").get("name").in(dto.getCategory()));
        }

        if (dto.getAlcohol() != null && !dto.getAlcohol().isEmpty()) {
            predicates.add(root.get("alcoholicEntity").get("name").in(dto.getAlcohol()));
        }

        if (dto.getNotHaveCount() != null) {
            List<Long> approveCocktail = findICountCocktailIds(dto.getNotHaveCount(), visitor, dto.getIngredient());
            predicates.add(root.get("id").in(approveCocktail));
        }
//
//        if (!dto.getSortField().equals("name") || !dto.getSortOrder().equals("asc")) {
//            cb.asc(root.get("name"));
////            query.orderBy(cb.asc(root.get("name").get(dto.getSortField())));
//        } else {
//            criteriaQuery.orderBy(cb.asc(root.get("name")));
//        }

        //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;
    }

    private List<Long> findICountCocktailIds(Integer iCount, Visitor visitor, List<String> ingredientFilter) {
        List<Long> allowedIngredient = new ArrayList<>();

        Stream<List<ReceiptEntity>> receiptStream = receiptRepository.findAll()
                .stream()
                .collect(Collectors.groupingBy(k -> k.getCocktail().getId()))
                .values()
                .stream()
                .filter(l -> getCountNotHaveIngredient(allowedIngredient, l).equals(iCount));

        if (!ingredientFilter.isEmpty()) {
            receiptStream = receiptStream.filter(l -> findIngredientInReceipts(ingredientFilter, l));
        }
        return receiptStream
                .map(l -> l.get(0))
                .map(ReceiptEntity::getCocktail)
                .map(CocktailEntity::getId)
                .toList();
    }

    private boolean findIngredientInReceipts(List<String> ingredientFilter, List<ReceiptEntity> receipts) {
        return receipts.stream().anyMatch(r -> ingredientFilter.contains(r.getIngredient().getName()));
    }

    private Integer getCountNotHaveIngredient(List<Long> allowedIngredientIds, List<ReceiptEntity> receipts) {
        return Math.toIntExact(receipts.size() - receipts.stream()
                .filter(r -> allowedIngredientIds.contains(r.getIngredient().getId()))
                .count());
    }

    private List<Long> getAllowedCocktailIds(Long barId) {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<Long> query = cb.createQuery(Long.class);

        Root<ReceiptEntity> receiptRoot = query.from(ReceiptEntity.class);
        Join<ReceiptEntity, IngredientEntity> ingredientJoin = receiptRoot.join("ingredient", JoinType.LEFT);
        Join<IngredientEntity, BarIngredientStorage> barIngredientStorageJoin = ingredientJoin.join("barIngredients", JoinType.LEFT);

        // Внешний подзапрос с NOT EXISTS
        Subquery<Long> subquery = query.subquery(Long.class);
        Root<ReceiptEntity> receiptSubRoot = subquery.from(ReceiptEntity.class);
        Join<ReceiptEntity, IngredientEntity> ingredientSubJoin = receiptSubRoot.join("ingredient", JoinType.LEFT);

        // Внутренний подзапрос с NOT EXISTS
        Subquery<Long> innerSubquery = subquery.subquery(Long.class);
        Root<BarIngredientStorage> barIngredientStorageInnerRoot = innerSubquery.from(BarIngredientStorage.class);

        // Условия внутреннего подзапроса
        innerSubquery.select(barIngredientStorageInnerRoot.get("id"))
                .where(
                        cb.equal(barIngredientStorageInnerRoot.get("ingredient"), ingredientSubJoin.get("id")),
                        cb.equal(barIngredientStorageInnerRoot.get("bar").get("id"), barId)
                );

        // Условия внешнего подзапроса
        subquery.select(receiptSubRoot.get("id"))
                .where(
                        cb.equal(receiptSubRoot.get("cocktail").get("id"), receiptRoot.get("cocktail").get("id")),
                        cb.not(cb.exists(innerSubquery))
                );

        // Основной запрос
        query.select(receiptRoot.get("cocktail").get("id"))
                .distinct(true)
                .where(
                        cb.equal(barIngredientStorageJoin.get("bar").get("id"), barId),
                        cb.not(cb.exists(subquery))
                );

        return entityManager.createQuery(query).getResultList();
    }

    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()));
        }

        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());
        repository.save(cocktail);

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

    public void editFavourite(Long cocktailId, boolean put) {
        cocktailRepository.updateFavouriteById(cocktailId, put);
    }

    public void setRating(Long cocktailId, Integer rating) {
        cocktailRepository.updateRatingById(cocktailId, rating);
    }

    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.setMeasure(receipt.getMeasure());
        receiptEntity.setCocktail(cocktail);
        receiptRepository.save(receiptEntity);
    }

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

    public List<ReceiptResponseDto> getReceipts(Long id) {

        return null;
    }

    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;
    }

    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();
    }

    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();
    }
}
