package com.example.bnsptest.ui

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.map
import androidx.lifecycle.viewModelScope
import com.example.bnsptest.data.local.dao.Product
import com.example.bnsptest.data.repository.ProductRepository
import kotlinx.coroutines.launch

class ProductViewModel(
    private val productRepository: ProductRepository
) : ViewModel() {

    val allProducts: LiveData<List<Product>> = productRepository.allProducts

    val catalogProducts: LiveData<List<Product>> = allProducts

    val cartProducts: LiveData<List<Product>> = allProducts.map { list ->
        list?.filter { it.isAddedToCart && it.quantity > 0 } ?: emptyList()
    }

    init {
        // This will insert the items if the DB is empty
        refreshProducts()
    }

    fun refreshProducts() {
        viewModelScope.launch {
            productRepository.insertInitialProducts()
        }
    }

    fun addToCart(product: Product) {
        viewModelScope.launch {
            val updatedProduct = product.copy(
                isAddedToCart = true,
                quantity = product.quantity + 1
            )
            productRepository.updateProduct(updatedProduct)
        }
    }

    fun increaseQuantity(product: Product) {
        viewModelScope.launch {
            productRepository.updateProduct(product.copy(quantity = product.quantity + 1))
        }
    }

    fun decreaseQuantity(product: Product) {
        viewModelScope.launch {
            if (product.quantity > 1) {
                productRepository.updateProduct(product.copy(quantity = product.quantity - 1))
            } else {
                productRepository.updateProduct(product.copy(isAddedToCart = false, quantity = 0))
            }
        }
    }

    fun checkout() {
        viewModelScope.launch {
            productRepository.clearCart()
        }
    }
}
