package com.rugvedsarika.privatelog.ui.editor

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.rugvedsarika.privatelog.data.model.Note
import com.rugvedsarika.privatelog.data.repository.NoteRepository
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

class EditorViewModel(private val repository: NoteRepository) : ViewModel() {

    private val _currentNote = MutableLiveData<Note?>()
    val currentNote: LiveData<Note?> = _currentNote

    fun loadNote(id: Long) {
        if (id == 0L) return
        viewModelScope.launch {
            val note = repository.getNoteById(id)
            _currentNote.value = note
        }
    }
    
    // NOTE: I'll update DAO immediately after this file creation to add getById.
    
    fun saveNote(title: String, content: String, id: Long = 0) {
        viewModelScope.launch {
            val timestamp = System.currentTimeMillis()
            val note = Note(
                id = id,
                title = title,
                content = content,
                timestamp = timestamp
            )
            if (id == 0L) {
                repository.insert(note)
            } else {
                repository.update(note)
            }
        }
    }
    
    suspend fun deleteNote(id: Long) {
         val note = repository.getNoteById(id)
         note?.let { repository.delete(it) }
    }
}

class EditorViewModelFactory(private val repository: NoteRepository) : ViewModelProvider.Factory {
     override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(EditorViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return EditorViewModel(repository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}
