package com.example.orderly.data.repository

import androidx.lifecycle.LiveData
import com.example.orderly.data.local.CartDao
import com.example.orderly.data.local.ProductDao
import com.example.orderly.data.local.UserDao
import com.example.orderly.data.entity.CartItem
import com.example.orderly.data.entity.Product
import com.example.orderly.data.entity.User
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class OrderLyRepository(
    private val productDao: ProductDao,
    private val cartDao: CartDao,
    private val userDao: UserDao
) {
    // Product CRUD
    val allProducts: LiveData<List<Product>> = productDao.getAllProducts()
    val favoriteProducts: LiveData<List<Product>> = productDao.getFavoriteProducts()

    suspend fun insertProducts(products: List<Product>) {
        productDao.insertProducts(products)
    }

    suspend fun updateProduct(product: Product) {
        productDao.updateProduct(product)
    }

    suspend fun deleteProduct(product: Product) {
        productDao.deleteProduct(product)
    }

    // Cart CRUD
    val cartItems: LiveData<List<CartItem>> = cartDao.getCartItems()

    suspend fun addToCart(product: Product) {
        val cartItem = CartItem(
            productId = product.id,
            productName = product.name,
            productPrice = product.price,
            quantity = 1,
            imageUrl = product.imageUrl
        )
        cartDao.addToCart(cartItem)
    }

    suspend fun updateCartQuantity(cartItem: CartItem, quantity: Int) {
        if (quantity > 0) {
            cartDao.updateCartItem(cartItem.copy(quantity = quantity))
        } else {
            cartDao.deleteCartItem(cartItem)
        }
    }

    suspend fun clearCart() {
        cartDao.clearCart()
    }

    // User CRUD
    val allUsers: LiveData<List<User>> = userDao.getAllUsers()
    suspend fun insertUser(user: User) {
        userDao.insertUser(user)
    }
    suspend fun login(email: String): User? {
        return withContext(Dispatchers.IO) {
            userDao.getUserByEmail(email)
        }
    }
}
