package com.fieldlabel.collector.data.local

import androidx.room.Entity
import androidx.room.PrimaryKey
import com.fieldlabel.collector.domain.model.CollectionRecord
import java.time.LocalDate
import java.time.LocalDateTime

@Entity(tableName = "collection_records")
data class CollectionRecordEntity(
    @PrimaryKey val id: String,
    val locationId: String,
    val specimenNumber: Int,
    val specimenId: String,
    val collectionDate: String,      // ISO-8601: "2026-05-12"
    val latitude: Double,
    val longitude: Double,
    val altitude: Double?,
    val address: String?,
    val collectorName: String,
    val notes: String,
    val synced: Boolean = false,
    val createdAt: String,           // ISO-8601 datetime
    /** 貼り付け先チューブの外径 (mm)。null = フラット面（補正なし） */
    val tubeDiameterMm: Float? = null
) {
    fun toDomain() = CollectionRecord(
        id = id,
        locationId = locationId,
        specimenNumber = specimenNumber,
        specimenId = specimenId,
        collectionDate = LocalDate.parse(collectionDate),
        latitude = latitude,
        longitude = longitude,
        altitude = altitude,
        address = address,
        collectorName = collectorName,
        notes = notes,
        synced = synced,
        createdAt = LocalDateTime.parse(createdAt),
        tubeDiameterMm = tubeDiameterMm
    )

    companion object {
        fun fromDomain(r: CollectionRecord) = CollectionRecordEntity(
            id = r.id,
            locationId = r.locationId,
            specimenNumber = r.specimenNumber,
            specimenId = r.specimenId,
            collectionDate = r.collectionDate.toString(),
            latitude = r.latitude,
            longitude = r.longitude,
            altitude = r.altitude,
            address = r.address,
            collectorName = r.collectorName,
            notes = r.notes,
            synced = r.synced,
            createdAt = r.createdAt.toString(),
            tubeDiameterMm = r.tubeDiameterMm
        )
    }
}
