package com.keylightpiano.pianotimeline.data

import com.keylightpiano.pianotimeline.data.remote.RecordingDto
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")

/**
 * Converts a raw DTO into a clean Recording.
 * Returns null if the entry is too broken to use (e.g. unparseable date),
 * so the caller can skip it instead of crashing the whole list.
 */
fun RecordingDto.toDomainOrNull(): Recording? {
    val parsedDate = try {
        LocalDate.parse(date.trim(), DATE_FORMAT)
    } catch (e: Exception) {
        return null   // a recording with no valid date is useless for sorting
    }

    return Recording(
        id = id,
        date = parsedDate,
        artist = artist.trim(),
        title = title.trim(),
        extraInfo = extraInfo.trim(),
        performanceNumber = performanceNumber.toIntOrNull() ?: 0,
        totalPerformances = totalPerformances.toIntOrNull() ?: 0,
        fileName = fileName,                       // keep raw — encoded only when building a URL
        midiFileName = midiFileName.ifBlank { null },
        durationSeconds = duration.toDoubleOrNull() ?: 0.0,
        soundStartSeconds = soundStart.toDoubleOrNull() ?: 0.0,
        fileSize = fileSize.toLongOrNull() ?: 0L
    )
}
