package com.example.myapplication.api.repository

import com.example.myapplication.api.MyServerService
import com.example.myapplication.api.model.toProductList
import com.example.myapplication.api.model.toUser
import com.example.myapplication.api.model.toUserProductRemote
import com.example.myapplication.api.model.toUserRemote
import com.example.myapplication.database.entities.User
import com.example.myapplication.database.entities.UserProductCart
import com.example.myapplication.database.entities.UserWithCartProduct

import com.example.myapplication.database.repository.UserRepository
class UserRestRepository(
    private val service: MyServerService
): UserRepository {
    override suspend fun getAll(): List<User> {
        return service.getAllUsers().map { it.toUser() }
    }

    override suspend fun getById(id: Int): User {
        return service.getUserById(id).toUser()
    }

    override suspend fun getByAuth(login: String, password: String): User? {
        val ans = service.getUserByAuth(login, password)
        return if(ans.isEmpty()) null
        else ans[0].toUser()
    }

    override suspend fun getUserProductCartById(id: Int): UserWithCartProduct {
        val products = service.getUserProductCartById(id).map { it.toProductList() }
        return UserWithCartProduct(service.getUserById(id).toUser(), products)
    }

    override suspend fun deleteCartProduct(userId: Int, productId: Int) {
        val product = service.getProductCart(userId, productId)[0]
        service.deleteCartProduct(product.id)
    }

    override suspend fun insert(user: User) {
        service.createUser(user.toUserRemote())
    }

    override suspend fun addProductCart(userProduct: UserProductCart) {
        val product = service.getProductCart(userProduct.userId, userProduct.productId)
        if(!product.isEmpty()) throw Exception("Уже добавлено")

        service.addProductCart(userProduct.toUserProductRemote())
    }
}