package com.diegocayo.organizame.data.repository

import com.diegocayo.organizame.data.local.dao.EventDao
import com.diegocayo.organizame.data.mapper.toEntity
import com.diegocayo.organizame.data.mapper.toModel
import com.diegocayo.organizame.domain.model.Event
import com.diegocayo.organizame.domain.repository.EventRepository
import com.diegocayo.organizame.domain.repository.SubjectRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.util.Calendar
import javax.inject.Inject

class EventRepositoryImpl @Inject constructor(
    private val eventDao: EventDao,
    private val subjectRepository: SubjectRepository
) : EventRepository {

    override fun getAllEvents(): Flow<List<Event>> {
        return eventDao.getAllEvents().map { entities ->
            entities.map { entity ->
                val subject = entity.subjectId?.let { id ->
                    subjectRepository.getSubjectById(id)
                }
                entity.toModel(subject)
            }
        }
    }

    override fun getEventsByDate(date: Long): Flow<List<Event>> {
        val calendar = Calendar.getInstance().apply {
            timeInMillis = date
            set(Calendar.HOUR_OF_DAY, 0)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }
        val startOfDay = calendar.timeInMillis

        calendar.add(Calendar.DAY_OF_MONTH, 1)
        val endOfDay = calendar.timeInMillis

        return eventDao.getEventsByDate(startOfDay, endOfDay).map { entities ->
            entities.map { entity ->
                val subject = entity.subjectId?.let { id ->
                    subjectRepository.getSubjectById(id)
                }
                entity.toModel(subject)
            }
        }
    }

    override suspend fun insertEvent(event: Event): Long {
        return eventDao.insertEvent(event.toEntity())
    }

    override suspend fun updateEvent(event: Event) {
        eventDao.updateEvent(event.toEntity())
    }

    override suspend fun deleteEvent(event: Event) {
        eventDao.deleteEvent(event.toEntity())
    }
} 