package com.syncflow.data.db.entities

import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.syncflow.domain.model.*
import java.time.Instant

@Entity(
    tableName = "sync_pairs",
    foreignKeys = [ForeignKey(
        entity = CloudAccountEntity::class,
        parentColumns = ["id"],
        childColumns = ["accountId"],
        onDelete = ForeignKey.CASCADE,
    )],
    indices = [Index("accountId")],
)
data class SyncPairEntity(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val name: String,
    val localPath: String,
    val remotePath: String,
    val accountId: Long,
    // Sync behaviour
    val syncDirection: SyncDirection,
    val conflictStrategy: ConflictStrategy,
    val deleteBehavior: DeleteBehavior,
    val recursive: Boolean,
    // Schedule
    val scheduleType: ScheduleType,
    val scheduleIntervalMinutes: Int,
    val scheduleDailyTime: String?,
    val scheduleWeekdays: Int,
    // Constraints
    val wifiOnly: Boolean,
    val wifiSsid: String,
    val chargingOnly: Boolean,
    val minBatteryPct: Int,
    // File filters (newline-separated lists stored as strings)
    val excludePatterns: String,
    val includeExtensions: String,
    val excludeExtensions: String,
    val skipHiddenFiles: Boolean,
    val minFileSizeKb: Long,
    val maxFileSizeKb: Long,
    // Notifications
    val notifyOnComplete: Boolean,
    val notifyOnError: Boolean,
    // State
    val isEnabled: Boolean,
    val lastSyncAt: Instant?,
    val lastSyncResult: SyncStatus,
    val pendingConflicts: Int,
    // Last sync outcome counters (persist across pause/resume)
    val lastSyncUploaded: Int = 0,
    val lastSyncDownloaded: Int = 0,
    val lastSyncDeleted: Int = 0,
    val lastSyncBytesTransferred: Long = 0L,
)

fun SyncPairEntity.toDomain() = SyncPair(
    id = id, name = name, localPath = localPath, remotePath = remotePath, accountId = accountId,
    syncDirection = syncDirection, conflictStrategy = conflictStrategy, deleteBehavior = deleteBehavior,
    recursive = recursive, scheduleType = scheduleType, scheduleIntervalMinutes = scheduleIntervalMinutes,
    scheduleDailyTime = scheduleDailyTime, scheduleWeekdays = scheduleWeekdays,
    wifiOnly = wifiOnly, wifiSsid = wifiSsid, chargingOnly = chargingOnly, minBatteryPct = minBatteryPct,
    excludePatterns = excludePatterns.splitList(), includeExtensions = includeExtensions.splitList(),
    excludeExtensions = excludeExtensions.splitList(), skipHiddenFiles = skipHiddenFiles,
    minFileSizeKb = minFileSizeKb, maxFileSizeKb = maxFileSizeKb,
    notifyOnComplete = notifyOnComplete, notifyOnError = notifyOnError,
    isEnabled = isEnabled, lastSyncAt = lastSyncAt, lastSyncResult = lastSyncResult, pendingConflicts = pendingConflicts,
)

private fun String.splitList() = if (isBlank()) emptyList() else trim().split("\n").filter { it.isNotBlank() }
