package com.fieldlabel.collector.data.local

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

@Dao
interface SpecimenPhotoDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(entity: SpecimenPhotoEntity)

    @Delete
    suspend fun delete(entity: SpecimenPhotoEntity)

    /** 地点IDに紐づく写真を撮影順で返す（Flow — UI観察用） */
    @Query("SELECT * FROM specimen_photos WHERE locationId = :locationId ORDER BY takenAt ASC")
    fun getByLocationIdFlow(locationId: String): Flow<List<SpecimenPhotoEntity>>

    /** 地点IDに紐づく写真を撮影順で返す（一回取得） */
    @Query("SELECT * FROM specimen_photos WHERE locationId = :locationId ORDER BY takenAt ASC")
    suspend fun getByLocationId(locationId: String): List<SpecimenPhotoEntity>

    /** 指定地点の全写真を削除する */
    @Query("DELETE FROM specimen_photos WHERE locationId = :locationId")
    suspend fun deleteByLocationId(locationId: String)

    /** 写真に紐づく標本IDを更新する（null = 地点全体に変更） */
    @Query("UPDATE specimen_photos SET specimenId = :specimenId WHERE id = :photoId")
    suspend fun updateTag(photoId: String, specimenId: String?)

    /** 全写真を撮影順で購読する（サムネイル表示用） */
    @Query("SELECT * FROM specimen_photos ORDER BY takenAt ASC")
    fun getAllPhotosFlow(): Flow<List<SpecimenPhotoEntity>>

    /** 地点ID＋メディア種別でフィルタして返す */
    @Query("SELECT * FROM specimen_photos WHERE locationId = :locationId AND mediaType = :mediaType ORDER BY takenAt ASC")
    fun getByLocationIdAndTypeFlow(locationId: String, mediaType: String): Flow<List<SpecimenPhotoEntity>>

    /** 全写真（mediaType='photo'のみ）をサムネイル表示用に返す */
    @Query("SELECT * FROM specimen_photos WHERE mediaType = 'photo' ORDER BY takenAt ASC")
    fun getAllPhotosOnlyFlow(): Flow<List<SpecimenPhotoEntity>>
}
