package com.safecheckin.app.data.repository

import android.content.Context
import com.safecheckin.app.data.api.ApiClient
import com.safecheckin.app.data.cloud.CloudDataSource
import com.safecheckin.app.data.model.CheckInRecord
import com.safecheckin.app.data.model.Contact
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow

class CloudRepository(context: Context) {
    
    private val apiClient = ApiClient(context)
    private val cloudDataSource = CloudDataSource(apiClient)

    // ========== 打卡相关 ==========
    
    suspend fun getCheckIns(): List<CheckInRecord> {
        return cloudDataSource.getCheckIns()
    }

    suspend fun insertCheckIn(note: String = ""): Boolean {
        return cloudDataSource.addCheckIn(note)
    }

    suspend fun getCheckInCount(): Int {
        return cloudDataSource.getCheckInCount()
    }

    // ========== 联系人相关 ==========
    
    suspend fun getContacts(): List<Contact> {
        return cloudDataSource.getContacts()
    }

    suspend fun insertContact(contact: Contact): Boolean {
        return cloudDataSource.addContact(contact)
    }

    suspend fun deleteContact(contactId: Int): Boolean {
        return cloudDataSource.deleteContact(contactId)
    }

    // ========== 设置相关 ==========
    
    suspend fun getGracePeriod(): Pair<Int, Int> {
        return cloudDataSource.getGracePeriod()
    }
    
    suspend fun setGracePeriod(hours: Int, minutes: Int): Boolean {
        return cloudDataSource.setGracePeriod(hours, minutes)
    }

    suspend fun getPresetMessage(): String {
        return cloudDataSource.getPresetMessage()
    }
    
    suspend fun setPresetMessage(message: String): Boolean {
        return cloudDataSource.setPresetMessage(message)
    }

    // ========== 每日提醒 ==========
    
    suspend fun getDailyReminder(): Boolean {
        return cloudDataSource.getDailyReminder()
    }
    
    suspend fun setDailyReminder(enabled: Boolean): Boolean {
        return cloudDataSource.setDailyReminder(enabled)
    }

    // ========== 账号注销 ==========
    
    suspend fun deleteAccount(): Boolean {
        return cloudDataSource.deleteAccount()
    }

    // ========== 用户统计 ==========
    
    suspend fun getUserStats(): Map<String, Any> {
        return cloudDataSource.getUserStats()
    }
    
    // ========== 登录状态 ==========
    
    suspend fun saveLoginState(userId: Int, email: String) {
        apiClient.saveLoginState(userId, email)
    }
    
    suspend fun clearLoginState() {
        apiClient.clearLoginState()
    }
    
    fun isLoggedIn(): Flow<Boolean> {
        return apiClient.isLoggedIn
    }
    
    fun getUserId(): Flow<Int> {
        return apiClient.userId
    }
    
    fun getUserEmail(): Flow<String> {
        return apiClient.userEmail
    }
    
    // ========== 服务器配置 ==========
    
    fun getBaseUrl(): Flow<String> {
        return apiClient.baseUrl
    }
    
    suspend fun setBaseUrl(url: String) {
        apiClient.setBaseUrl(url)
    }
}