package com.keylightpiano.pianotimeline.data.local

import com.keylightpiano.pianotimeline.domain.Recording
import java.time.LocalDate
import java.time.format.DateTimeFormatter

private val DATE_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy")

fun RecordingEntity.toDomainOrNull(): Recording? {
    val parsedDate = try {
        LocalDate.parse(date.trim(), DATE_FORMAT)
    } catch (e: Exception) {
        return null
    }

    return Recording(
        id = id,
        date = parsedDate,
        artist = artist,
        title = title,
        extraInfo = extraInfo,
        performanceNumber = performanceNumber,
        totalPerformances = totalPerformances,
        fileName = fileName,
        midiFileName = midiFileName,
        durationSeconds = durationSeconds,
        soundStartSeconds = soundStartSeconds,
        fileSize = fileSize,
        isFavorite = isFavorite,
        isNew = isNew,
        favoritedAt = favoritedAt,
        isCached = cachedAudioPath != null
    )
}

/**
 * Domain -> Entity. cachedAudioPath/cachedMidiPath and the local flags
 * default to their "fresh" values; callers preserve existing ones where needed.
 */
fun Recording.toEntity(
    cachedAudioPath: String? = null,
    cachedMidiPath: String? = null,
    isFavorite: Boolean = false,
    isNew: Boolean = false,
    favoritedAt: Long = 0L
): RecordingEntity = RecordingEntity(
    id = id,
    date = date.format(DATE_FORMAT),
    artist = artist,
    title = title,
    extraInfo = extraInfo,
    performanceNumber = performanceNumber,
    totalPerformances = totalPerformances,
    fileName = fileName,
    midiFileName = midiFileName,
    durationSeconds = durationSeconds,
    soundStartSeconds = soundStartSeconds,
    fileSize = fileSize,
    cachedAudioPath = cachedAudioPath,
    cachedMidiPath = cachedMidiPath,
    isFavorite = isFavorite,
    isNew = isNew,
    favoritedAt = favoritedAt
)
