package com.gestoreasy.services

import android.content.Context
import com.gestoreasy.database.entities.CheckIn
import com.gestoreasy.repository.CheckInRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Serviço para gerenciamento de check-in/check-out
 */
class CheckInService(
    private val context: Context,
    private val checkInRepository: CheckInRepository,
    private val locationService: LocationService
) {
    
    /**
     * Realiza check-in no endereço do cliente
     */
    suspend fun checkIn(
        clientId: Long?,
        address: String?,
        observations: String? = null
    ): CheckIn? {
        val location = locationService.getCurrentLocation()
        
        if (location == null) {
            return null // Não foi possível obter localização
        }
        
        val checkIn = CheckIn(
            id = 0,
            client_id = clientId,
            tipo = "checkin",
            latitude = location.latitude,
            longitude = location.longitude,
            accuracy = location.accuracy,
            endereco = address,
            observacoes = observations,
            synced = false
        )
        
        val id = checkInRepository.insert(checkIn)
        return checkIn.copy(id = id)
    }
    
    /**
     * Realiza check-out do endereço do cliente
     */
    suspend fun checkOut(
        clientId: Long?,
        address: String?,
        observations: String? = null
    ): CheckIn? {
        val location = locationService.getCurrentLocation()
        
        if (location == null) {
            return null
        }
        
        val checkOut = CheckIn(
            id = 0,
            client_id = clientId,
            tipo = "checkout",
            latitude = location.latitude,
            longitude = location.longitude,
            accuracy = location.accuracy,
            endereco = address,
            observacoes = observations,
            synced = false
        )
        
        val id = checkInRepository.insert(checkOut)
        return checkOut.copy(id = id)
    }
    
    /**
     * Obtém histórico de check-ins de um cliente
     */
    suspend fun getClientHistory(clientId: Long): List<CheckIn> {
        return checkInRepository.getByClient(clientId)
    }
}

