package com.fieldlabel.collector.ui.viewmodel

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fieldlabel.collector.data.CollectionRepository
import com.fieldlabel.collector.domain.model.CollectionRecord
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

@HiltViewModel
class MediaPreviewViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle,
    private val repository: CollectionRepository
) : ViewModel() {

    /** ナビゲーション引数から取得 */
    val locationId: String = savedStateHandle["locationId"] ?: ""
    val specimenId: String = savedStateHandle["specimenId"] ?: ""

    /**
     * 地点の代表レコード（住所・採集日・採集者名取得用）。
     * locationId が空の場合は null を流す。
     */
    val locationRecord: StateFlow<CollectionRecord?> = flow {
        if (locationId.isBlank()) {
            emit(null)
        } else {
            val records = repository.getByLocationId(locationId)
            emit(records.firstOrNull())
        }
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
}
