package com.example.skychasemk.services;

import com.example.skychasemk.dto.WishlistDTO;
import com.example.skychasemk.model.Flight;
import com.example.skychasemk.model.Wishlist;
import com.example.skychasemk.repository.FlightRepository;
import com.example.skychasemk.repository.WishlistRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
public class WishlistService {

    @Autowired
    private WishlistRepository wishlistRepository;

    @Autowired
    private FlightRepository flightRepository;

    public List<Wishlist> getAllWishlists() {
        return wishlistRepository.findAll();
    }

    public Wishlist saveWishlist(Wishlist wishlist) {
        return wishlistRepository.save(wishlist);
    }

    public void deleteWishlist(Integer wishlistID) {
        wishlistRepository.deleteById(wishlistID);
    }

    public void updateWishlist(WishlistDTO wishlistRequest) {
        Flight flight = flightRepository.findById(Long.valueOf(wishlistRequest.getTargetID()))
                .orElseThrow(() -> new IllegalArgumentException("Flight not found"));

        if (wishlistRequest.isWishlisted()) {
            Wishlist existingItem = wishlistRepository.findByTargetIdAndUserId(wishlistRequest.getTargetID(), wishlistRequest.getUserID());

            if (existingItem == null) {
                Wishlist newWishlistItem = new Wishlist();
                newWishlistItem.setTargetID(Math.toIntExact(wishlistRequest.getTargetID()));
                newWishlistItem.setUserID(wishlistRequest.getUserID());
                newWishlistItem.setDateAdded(LocalDate.now());
                wishlistRepository.save(newWishlistItem);
            }
        } else {
            Wishlist existingItem = wishlistRepository.findByTargetIdAndUserId(wishlistRequest.getTargetID(), wishlistRequest.getUserID());

            if (existingItem != null) {
                wishlistRepository.delete(existingItem);
            }
        }
    }

}

