package com.example.myapplication.api.item

import com.example.myapplication.api.MyServerService
import com.example.myapplication.database.entities.model.Item
import com.example.myapplication.database.entities.repository.OfflineRentItemRepository
import com.example.myapplication.database.entities.repository.OfflineItemRepository
import com.example.myapplication.database.entities.repository.OfflineUserItemRepository
import com.example.myapplication.database.entities.repository.ItemRepository

class RestItemRepository(
    private val service: MyServerService,
    private val dbItemRepository: OfflineItemRepository,
    private val dbUserItemRepository: OfflineUserItemRepository,
    private val dbRentItemRepository: OfflineRentItemRepository,
) : ItemRepository {
    override suspend fun getItem(uid: Int): Item {
        return service.getItem(uid).toItem()
    }

    override suspend fun insertItem(item: Item) {
        dbItemRepository.insertItem(
            service.createItem(item.toItemRemote()).toItem()
        )
    }

    override suspend fun updateItem(item: Item) {
        dbItemRepository.updateItem(
            service.updateItem(
                item.uid,
                item.toItemRemote()
            ).toItem()
        )
    }

    override suspend fun deleteItem(item: Item) {
        val cart = service.getUsers()
        cart.forEach { userRemote ->
            userRemote.items = userRemote.items.filter { x -> x.id != item.uid }
            userRemote.id?.let { service.updateUserCart(it, userRemote) }
        }
        val rents = service.getRents()
        rents.forEach { rentRemote ->
            rentRemote.items = rentRemote.items.filter { x -> x.id != item.uid }
            service.updateRent(rentRemote.id, rentRemote)
        }
        service.deleteItem(item.uid)
        dbUserItemRepository.deleteItemsByUid(item.uid)
        dbRentItemRepository.deleteItemsByUid(item.uid)
        dbItemRepository.deleteItem(item)
    }
}