package com.example.myapplication.api.rentitem

import com.example.myapplication.api.MyServerService
import com.example.myapplication.api.item.ItemFromRentRemote
import com.example.myapplication.api.item.toItem
import com.example.myapplication.database.entities.model.RentItemCrossRef
import com.example.myapplication.database.entities.repository.OfflineRentItemRepository
import com.example.myapplication.database.entities.repository.RentItemRepository

class RestRentItemRepository(
    private val service: MyServerService,
    private val dbRentItemRepository: OfflineRentItemRepository
) : RentItemRepository {
    override suspend fun insertRentItem(rentItemCrossRef: RentItemCrossRef) {
        var rentRemote = service.getRent(rentItemCrossRef.rentId)
        val item = service.getItem(rentItemCrossRef.itemId).toItem()

        val itemFromRent = ItemFromRentRemote(
            item.uid,
            item.dateTime,
            item.weight,
            rentItemCrossRef.count,
            item.bikeId
        )

        val updatedItems = rentRemote.items.toMutableList()
        updatedItems.add(itemFromRent)

        rentRemote = rentRemote.copy(items = updatedItems)
        service.updateRent(rentItemCrossRef.rentId, rentRemote)
        dbRentItemRepository.insertRentItem(rentItemCrossRef)
    }

    override suspend fun updateRentItem(rentItemCrossRef: RentItemCrossRef) {
    }

    override suspend fun deleteRentItem(rentItemCrossRef: RentItemCrossRef) {
    }
}