package com.carmaintenance.data.repository

import com.carmaintenance.data.model.Appointment
import com.carmaintenance.data.remote.ApiResponse
import com.carmaintenance.data.remote.ApiService
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class AppointmentRepository @Inject constructor(
    private val apiService: ApiService
) {
    suspend fun getAppointments(): Result<List<Appointment>> {
        return try {
            val response = apiService.getAppointments()
            if (response.isSuccess) {
                Result.success(response.data ?: emptyList())
            } else {
                Result.failure(Exception(response.message ?: "获取预约列表失败"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun getCustomerAppointments(customerId: Int): Result<List<Appointment>> {
        return try {
            val response = apiService.getAppointmentsByCustomer(customerId)
            if (response.isSuccess) {
                Result.success(response.data ?: emptyList())
            } else {
                Result.failure(Exception(response.message ?: "获取预约列表失败"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun createAppointment(appointment: Appointment): Result<Appointment> {
        return try {
            val response = apiService.createAppointment(appointment)
            if (response.isSuccess && response.data != null) {
                Result.success(response.data)
            } else {
                Result.failure(Exception(response.message ?: "创建预约失败"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun cancelAppointment(appointmentId: Int): Result<Unit> {
        return try {
            val response = apiService.cancelAppointment(appointmentId)
            if (response.isSuccess) {
                Result.success(Unit)
            } else {
                Result.failure(Exception(response.message ?: "取消预约失败"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}
