package com.smyhub.store.mengyastorebackendjava.service;

import com.smyhub.store.mengyastorebackendjava.dto.response.WishlistResponse;
import com.smyhub.store.mengyastorebackendjava.entity.Wishlist;
import com.smyhub.store.mengyastorebackendjava.exception.BusinessException;
import com.smyhub.store.mengyastorebackendjava.repository.WishlistRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class WishlistService {

    private final WishlistRepository wishlistRepository;

    public List<String> getWishlistIds(String accountId) {
        return wishlistRepository.findByAccountId(accountId).stream()
                .map(Wishlist::getProductId)
                .toList();
    }

    public List<WishlistResponse> getWishlist(String accountId) {
        return wishlistRepository.findByAccountId(accountId).stream()
                .map(this::toResponse)
                .toList();
    }

    @Transactional
    public WishlistResponse addToWishlist(String accountId, String productId) {
        if (wishlistRepository.existsByAccountIdAndProductId(accountId, productId)) {
            throw new BusinessException("该商品已在心愿单中");
        }
        try {
            Wishlist saved = wishlistRepository.save(new Wishlist(accountId, productId));
            return toResponse(saved);
        } catch (DataIntegrityViolationException e) {
            throw new BusinessException("该商品已在心愿单中");
        }
    }

    @Transactional
    public void removeFromWishlist(String accountId, String productId) {
        if (!wishlistRepository.existsByAccountIdAndProductId(accountId, productId)) {
            throw new BusinessException("心愿单中不存在该商品", HttpStatus.NOT_FOUND);
        }
        wishlistRepository.deleteByAccountIdAndProductId(accountId, productId);
    }

    private WishlistResponse toResponse(Wishlist w) {
        return WishlistResponse.builder()
                .id(w.getId())
                .accountId(w.getAccountId())
                .productId(w.getProductId())
                .build();
    }
}
