package pl.firmatpp.kierowca.data.upload

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query

@Dao
interface RoutePointDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(point: RoutePointEntity)

    @Query(
        """
        SELECT * FROM route_points
        WHERE routeId = :routeId
        AND status != 'CONFIRMED'
        ORDER BY timestamp ASC
        LIMIT :limit
        """,
    )
    suspend fun pendingForRoute(routeId: String, limit: Int): List<RoutePointEntity>

    @Query(
        """
        SELECT COUNT(*) FROM route_points
        WHERE routeId = :routeId
        AND status != 'CONFIRMED'
        """,
    )
    suspend fun pendingCount(routeId: String): Int

    @Query(
        """
        UPDATE route_points
        SET status = :status,
            lastError = :lastError,
            attemptCount = attemptCount + :attemptIncrement,
            updatedAtEpochMillis = :updatedAt
        WHERE clientPointId IN (:clientPointIds)
        """,
    )
    suspend fun updateStatus(
        clientPointIds: List<String>,
        status: String,
        lastError: String?,
        attemptIncrement: Int,
        updatedAt: Long = System.currentTimeMillis(),
    )
}
