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 SessionStatus {
    ACTIVE,
    COMPLETED,
    PAUSED
}

@Entity(
    tableName = "climb_sessions",
    foreignKeys = [
        ForeignKey(
            entity = Gym::class,
            parentColumns = ["id"],
            childColumns = ["gymId"],
            onDelete = ForeignKey.CASCADE
        )
    ],
    indices = [Index(value = ["gymId"])]
)
@Serializable
data class ClimbSession(
    @PrimaryKey
    val id: String,
    val gymId: String,
    val date: String, // ISO date string
    val startTime: String? = null, // When session was started
    val endTime: String? = null, // When session was completed
    val duration: Long? = null, // Duration in minutes (calculated when completed)
    val status: SessionStatus = SessionStatus.ACTIVE,
    val notes: String? = null,
    val createdAt: String,
    val updatedAt: String
) {
    companion object {
        fun create(
            gymId: String,
            notes: String? = null
        ): ClimbSession {
            val now = LocalDateTime.now().toString()
            return ClimbSession(
                id = java.util.UUID.randomUUID().toString(),
                gymId = gymId,
                date = now,
                startTime = now,
                status = SessionStatus.ACTIVE,
                notes = notes,
                createdAt = now,
                updatedAt = now
            )
        }
        
        fun ClimbSession.complete(): ClimbSession {
            val endTime = LocalDateTime.now().toString()
            val durationMinutes = if (startTime != null) {
                try {
                    val start = LocalDateTime.parse(startTime)
                    val end = LocalDateTime.parse(endTime)
                    java.time.Duration.between(start, end).toMinutes()
                } catch (e: Exception) {
                    null
                }
            } else null
            
            return this.copy(
                endTime = endTime,
                duration = durationMinutes,
                status = SessionStatus.COMPLETED,
                updatedAt = LocalDateTime.now().toString()
            )
        }
    }
}
