package ru.kayashov.bar.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import ru.kayashov.bar.controller.dto.cocktail.ReceiptResponseDto;
import ru.kayashov.bar.controller.dto.ingredient.IngredientSimpleResponseDto;
import ru.kayashov.bar.model.entity.CocktailEntity;
import ru.kayashov.bar.model.entity.Visitor;
import ru.kayashov.bar.repository.CocktailRepository;
import ru.kayashov.bar.repository.VisitorsRepository;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SessionService {

    private final VisitorsRepository visitorsRepository;
    private final CocktailRepository cocktailRepository;

    public Visitor getVisitor() {
        Long id = ((Visitor) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal())
                .getId();
        return visitorsRepository.findById(id)
                .orElseThrow();
    }

    public List<ReceiptResponseDto> getReceiptList(Long cocktailId) {
        CocktailEntity cocktail = cocktailRepository.findById(cocktailId).orElseThrow();
        return cocktail.getReceipt().stream()
                .map(e -> ReceiptResponseDto.builder()
                        .id(e.getId())
                        .ingredient(IngredientSimpleResponseDto.mapToDto(e.getIngredient()))
                        .measure(e.getMeasure())
                        .build())
                .toList();
    }
}
