package com.example.ops_android.data.repository

import com.example.ops_android.data.model.Customer
import com.example.ops_android.data.remote.api.CustomerApi
import com.example.ops_android.data.remote.api.CustomerGetRequest
import com.example.ops_android.data.remote.api.CustomerListRequest

class CustomerRepository(
    private val customerApi: CustomerApi
) {
    suspend fun list(search: String? = null): Result<List<Customer>> {
        return try {
            val response = customerApi.list(CustomerListRequest(search = search, page_size = if (search != null) 10 else 5))
            if (response.errCode == 0 && response.data != null) {
                Result.success(response.data.customers ?: emptyList())
            } else {
                Result.failure(Exception("获取客户列表失败"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun get(id: Int): Result<Customer> {
        return try {
            val response = customerApi.get(CustomerGetRequest(id))
            if (response.errCode == 0 && response.data?.customer != null) {
                Result.success(response.data.customer)
            } else {
                Result.failure(Exception("获取客户详情失败"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun add(data: Map<String, Any>): Result<Unit> {
        return try {
            val response = customerApi.add(data)
            if (response.errCode == 0) Result.success(Unit)
            else Result.failure(Exception("创建客户失败"))
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun update(data: Map<String, Any>): Result<Unit> {
        return try {
            val response = customerApi.update(data)
            if (response.errCode == 0) Result.success(Unit)
            else Result.failure(Exception("更新客户失败"))
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun delete(id: Int): Result<Unit> {
        return try {
            val response = customerApi.delete(mapOf("id" to id))
            if (response.errCode == 0) Result.success(Unit)
            else Result.failure(Exception("删除客户失败"))
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}
