package com.atridad.openclimb.data.model

import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import kotlinx.serialization.Serializable
import java.time.LocalDateTime

@Serializable
enum class AttemptResult {
    SUCCESS,        // Completed the problem/route
    FALL,          // Fell but made progress
    NO_PROGRESS,   // Couldn't make meaningful progress
    FLASH,         // Completed on first try
    REDPOINT,      // Completed after previous attempts
    ONSIGHT        // Completed on first try without prior knowledge
}

@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"])
    ]
)
@Serializable
data class Attempt(
    @PrimaryKey
    val id: String,
    val sessionId: String,
    val problemId: String,
    val result: AttemptResult,
    val highestHold: String? = null, // Description of the highest hold reached
    val notes: String? = null,
    val duration: Long? = null, // Attempt duration in seconds
    val restTime: Long? = null, // Rest time before this attempt in seconds
    val timestamp: String, // When this attempt was made
    val createdAt: 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 = LocalDateTime.now().toString()
        ): Attempt {
            val now = LocalDateTime.now().toString()
            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
            )
        }
    }
}
