package com.atridad.ascently.data.model

import androidx.compose.runtime.Immutable
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.atridad.ascently.utils.DateFormatUtils
import kotlinx.serialization.Serializable

@Serializable
enum class AttemptResult {
    SUCCESS,
    FALL,
    NO_PROGRESS,
    FLASH,
}

@Entity(
    tableName = "attempts",
    foreignKeys =
    [
        ForeignKey(
            entity = ClimbSession::class,
            parentColumns = ["id"],
            childColumns = ["sessionId"],
            onDelete = ForeignKey.CASCADE,
        ),
        ForeignKey(
            entity = Problem::class,
            parentColumns = ["id"],
            childColumns = ["problemId"],
            onDelete = ForeignKey.CASCADE,
        ),
    ],
    indices = [Index(value = ["sessionId"]), Index(value = ["problemId"])],
)
@Immutable
@Serializable
data class Attempt(
    @PrimaryKey val id: String,
    val sessionId: String,
    val problemId: String,
    val result: AttemptResult,
    val highestHold: String? = null,
    val notes: String? = null,
    val duration: Long? = null,
    val restTime: Long? = null,
    val timestamp: String,
    val createdAt: String,
    val updatedAt: String,
) {
    companion object {
        fun create(
            sessionId: String,
            problemId: String,
            result: AttemptResult,
            highestHold: String? = null,
            notes: String? = null,
            duration: Long? = null,
            restTime: Long? = null,
            timestamp: String = DateFormatUtils.nowISO8601(),
        ): Attempt {
            val now = DateFormatUtils.nowISO8601()
            return Attempt(
                id = java.util.UUID.randomUUID().toString(),
                sessionId = sessionId,
                problemId = problemId,
                result = result,
                highestHold = highestHold,
                notes = notes,
                duration = duration,
                restTime = restTime,
                timestamp = timestamp,
                createdAt = now,
                updatedAt = now,
            )
        }
    }
}
