package com.diegocayo.organizame.data.repository

import com.diegocayo.organizame.data.local.dao.TaskDao
import com.diegocayo.organizame.data.local.entity.TaskStatus
import com.diegocayo.organizame.data.mapper.toEntity
import com.diegocayo.organizame.data.mapper.toModel
import com.diegocayo.organizame.domain.model.Task
import com.diegocayo.organizame.domain.repository.SubjectRepository
import com.diegocayo.organizame.domain.repository.TaskRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject

class TaskRepositoryImpl @Inject constructor(
    private val taskDao: TaskDao,
    private val subjectRepository: SubjectRepository
) : TaskRepository {
    override fun getAllTasks(): Flow<List<Task>> {
        return taskDao.getAllTasks().map { tasks ->
            tasks.map { taskEntity ->
                val subject = taskEntity.subjectId?.let { id ->
                    subjectRepository.getSubjectById(id)
                }
                taskEntity.toModel(subject)
            }
        }
    }

    override fun getPendingTasks(): Flow<List<Task>> {
        return taskDao.getPendingTasks().map { tasks ->
            tasks.map { taskEntity ->
                val subject = taskEntity.subjectId?.let { id ->
                    subjectRepository.getSubjectById(id)
                }
                taskEntity.toModel(subject)
            }
        }
    }

    override fun getCompletedTasks(): Flow<List<Task>> {
        return taskDao.getCompletedTasks().map { tasks ->
            tasks.map { taskEntity ->
                val subject = taskEntity.subjectId?.let { id ->
                    subjectRepository.getSubjectById(id)
                }
                taskEntity.toModel(subject)
            }
        }
    }

    override suspend fun getTaskById(taskId: Long): Task? {
        return taskDao.getTaskById(taskId)?.let { taskEntity ->
            val subject = taskEntity.subjectId?.let { id ->
                subjectRepository.getSubjectById(id)
            }
            taskEntity.toModel(subject)
        }
    }

    override suspend fun insertTask(task: Task): Long {
        return taskDao.insertTask(task.toEntity())
    }

    override suspend fun updateTask(task: Task) {
        taskDao.updateTask(task.toEntity())
    }

    override suspend fun deleteTask(task: Task) {
        taskDao.deleteTask(task.toEntity())
    }

    override suspend fun updateTaskStatus(taskId: Long, status: TaskStatus) {
        taskDao.updateTaskStatus(taskId, status.name)
    }
} 