package com.example.shiftalarm

import android.content.Context
import java.time.LocalDate
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class ShiftRepository(private val context: Context) {
    private val db = AppDatabase.getDatabase(context)
    private val dao = db.shiftDao()

    suspend fun getShift(date: LocalDate, team: String, factory: String): String = withContext(Dispatchers.IO) {
        val override = dao.getOverride(factory, team, date.toString())
        if (override != null) {
            return@withContext override.shift
        }
        ShiftCalculator.getShift(date, team, factory)
    }

    suspend fun setOverride(date: LocalDate, shift: String, team: String, factory: String) {
        dao.insertOverride(ShiftOverride(factory, team, date.toString(), shift))
    }

    suspend fun clearOverride(date: LocalDate, team: String, factory: String) {
        dao.deleteOverride(factory, team, date.toString())
    }

    suspend fun getMemo(date: LocalDate): String? {
        return dao.getMemo(date.toString())?.content
    }

    suspend fun setMemo(date: LocalDate, content: String) {
        if (content.isEmpty()) {
            dao.deleteMemo(date.toString())
        } else {
            dao.insertMemo(DailyMemo(date.toString(), content))
        }
    }

    // Custom Alarms
    suspend fun getAllCustomAlarms(): List<CustomAlarm> = withContext(Dispatchers.IO) {
        dao.getAllCustomAlarms()
    }

    suspend fun addCustomAlarm(alarm: CustomAlarm): Long = withContext(Dispatchers.IO) {
        dao.insertCustomAlarm(alarm)
    }

    suspend fun updateCustomAlarm(alarm: CustomAlarm) = withContext(Dispatchers.IO) {
        dao.updateCustomAlarm(alarm)
    }

    suspend fun deleteCustomAlarm(alarm: CustomAlarm) = withContext(Dispatchers.IO) {
        dao.deleteCustomAlarm(alarm)
    }

    suspend fun clearAllCustomAlarms() = withContext(Dispatchers.IO) {
        dao.clearCustomAlarms()
    }

 // Annual Leave
 suspend fun calculateUsedAnnualLeave(): Float = withContext(Dispatchers.IO) {
 val currentYear = java.time.Year.now(java.time.ZoneId.of("Asia/Seoul")).toString()
 val overrides = dao.getAllOverrides()

 var usedDays = 0f

 for (override in overrides) {
 if (override.date.startsWith(currentYear)) {
 when (override.shift) {
 "연차" -> usedDays += 1f
 "반년" -> usedDays += 0.5f
 }
 }
 }

 usedDays
 }

    suspend fun getAnnualLeave(): AnnualLeave? = withContext(Dispatchers.IO) {
        dao.getAnnualLeave()
    }

    suspend fun recalculateAndSaveAnnualLeave(totalDays: Float) {
        val usedDays = calculateUsedAnnualLeave()
        val remainingDays = totalDays - usedDays
        
        dao.insertAnnualLeave(AnnualLeave(
            id = 1,
            totalDays = totalDays,
            remainingDays = remainingDays
        ))
    }

    suspend fun updateRemainingAnnualLeave() {
        val annualLeave = dao.getAnnualLeave()
        val usedDays = calculateUsedAnnualLeave()
        
        if (annualLeave != null) {
            val remainingDays = annualLeave.totalDays - usedDays
            dao.insertAnnualLeave(annualLeave.copy(remainingDays = remainingDays))
        } else {
            // AnnualLeave가 없으면 기본값 15일로 생성
            dao.insertAnnualLeave(AnnualLeave(
                id = 1,
                totalDays = 15f,
                remainingDays = 15f - usedDays
            ))
        }
    }
}
