package com.example.myapplication.api.useritem

import com.example.myapplication.api.MyServerService
import com.example.myapplication.api.item.ItemFromCartRemote
import com.example.myapplication.api.item.toItem
import com.example.myapplication.database.entities.model.UserItemCrossRef
import com.example.myapplication.database.entities.repository.OfflineUserItemRepository
import com.example.myapplication.database.entities.repository.UserItemRepository

class RestUserItemRepository(
    private val service: MyServerService,
    private val dbUserItemRepository: OfflineUserItemRepository
) : UserItemRepository {
    override suspend fun insertUserItem(userItemCrossRef: UserItemCrossRef) {
        var cartItems = service.getUserCart(userItemCrossRef.userId)
        cartItems.items.forEach { item ->
            if (item.id == userItemCrossRef.itemId)
                return
        }
        val item = service.getItem(userItemCrossRef.itemId).toItem()

        val itemFromCart = ItemFromCartRemote(
            item.uid,
            userItemCrossRef.count,
            item.bikeId,
        )

        val updatedItems = cartItems.items.toMutableList()
        updatedItems.add(itemFromCart)

        cartItems = cartItems.copy(items = updatedItems)
        service.updateUserCart(userItemCrossRef.userId, cartItems)
        dbUserItemRepository.insertUserItem(userItemCrossRef)
    }

    override suspend fun updateUserItem(userItemCrossRef: UserItemCrossRef) {
        val userRemote = service.getUserCart(userItemCrossRef.userId)
        if (userItemCrossRef.count <= 0) {
            userRemote.items =
                userRemote.items.filter { x -> x.id != userItemCrossRef.itemId }
        } else
            userRemote.items.forEach {
                if (it.id == userItemCrossRef.itemId) {
                    it.count = userItemCrossRef.count
                }
            }
        service.updateUserCart(userItemCrossRef.userId, userRemote)
        dbUserItemRepository.updateUserItem(userItemCrossRef)
    }

    override suspend fun deleteUserItem(userItemCrossRef: UserItemCrossRef) {
        updateUserItem(userItemCrossRef)
        dbUserItemRepository.deleteUserItem(userItemCrossRef)
    }

    override suspend fun deleteUserItems(userId: Int) {
        val userRemote = service.getUserCart(userId)
        userRemote.items = emptyList()
        service.updateUserCart(userId, userRemote)
        dbUserItemRepository.deleteUserItems(userId)
    }
}