package com.fieldlabel.collector.data.local

import androidx.room.*
import kotlinx.coroutines.flow.Flow

// ──────────────────────────────────────────────────────────────────────────────
// RouteLogDao  — 移動ログ概要テーブル
// ──────────────────────────────────────────────────────────────────────────────

@Dao
interface RouteLogDao {

    @Query("SELECT * FROM route_logs ORDER BY startTime DESC")
    fun getAllFlow(): Flow<List<RouteLogEntity>>

    @Query("SELECT * FROM route_logs WHERE id = :id")
    suspend fun getById(id: String): RouteLogEntity?

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(log: RouteLogEntity)

    @Query("""
        UPDATE route_logs
        SET endTime = :endTime, totalDistanceMeters = :distance, pointCount = :count
        WHERE id = :id
    """)
    suspend fun finishLog(id: String, endTime: Long, distance: Double, count: Int)

    @Query("DELETE FROM route_logs WHERE id = :id")
    suspend fun deleteById(id: String)

    @Query("SELECT * FROM route_logs ORDER BY startTime ASC")
    suspend fun getAllOnce(): List<RouteLogEntity>
}

// ──────────────────────────────────────────────────────────────────────────────
// RoutePointDao  — 測位点テーブル
// ──────────────────────────────────────────────────────────────────────────────

@Dao
interface RoutePointDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(point: RoutePointEntity)

    @Query("SELECT * FROM route_points WHERE routeLogId = :routeLogId ORDER BY timestamp ASC")
    fun getByRouteLogIdFlow(routeLogId: String): Flow<List<RoutePointEntity>>

    @Query("SELECT * FROM route_points WHERE routeLogId = :routeLogId ORDER BY timestamp ASC")
    suspend fun getByRouteLogId(routeLogId: String): List<RoutePointEntity>

    @Query("DELETE FROM route_points WHERE routeLogId = :routeLogId")
    suspend fun deleteByRouteLogId(routeLogId: String)

    @Query("SELECT * FROM route_points ORDER BY timestamp ASC")
    suspend fun getAllOnce(): List<RoutePointEntity>
}
