package id.iiyh.inatrading.feature.product.data.repository

import id.iiyh.inatrading.core.data.remote.ApiService
import id.iiyh.inatrading.feature.product.data.model.ProductDetail
import id.iiyh.inatrading.feature.product.domain.ProductPage
import id.iiyh.inatrading.feature.product.domain.ProductRepository
import javax.inject.Inject

class ProductRepositoryImpl @Inject constructor(
    private val apiService: ApiService,
) : ProductRepository {

    override suspend fun getProducts(page: Int, limit: Int): Result<ProductPage> {
        return try {
            val response = apiService.getProducts(page = page, limit = limit)
            if (response.isSuccess) {
                Result.success(
                    ProductPage(
                        items = response.rows,
                        totalItem = response.totalItem,
                        totalPage = response.totalPage,
                    )
                )
            } else {
                Result.failure(Exception(response.responseDesc ?: "Gagal memuat produk"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    override suspend fun getProductDetail(productId: String): Result<ProductDetail> {
        return try {
            val response = apiService.getProductDetail(productId = productId)
            if (!response.isSuccess) {
                return Result.failure(Exception(response.responseDesc ?: "Gagal memuat detail produk"))
            }
            val data = response.data
                ?: return Result.failure(Exception("Detail produk tidak ditemukan"))
            Result.success(data)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}
