package org.octopus.internal.repositories.impl

import org.octopus.internal.common.enums.EBusinessException
import org.octopus.internal.common.exceptions.OctopusPlanningException
import org.octopus.internal.common.mappers.ReportMapper
import org.octopus.internal.common.models.Report
import org.octopus.internal.db.ReportJpa
import org.octopus.internal.repositories.ReportRepository
import org.springframework.stereotype.Component
import java.util.*

@Component
class ReportRepositoryImpl(
    private val jpa: ReportJpa,
    private val mapper: ReportMapper
) : ReportRepository {

    override fun getById(id: Long): Report {
        return mapper.toModel(
            jpa.findById(id).orElseThrow {
                OctopusPlanningException.create(
                    EBusinessException.ENTITY_WITH_ID_NOT_FOUND,
                    Report::class.java.simpleName,
                    id
                )
            })
    }

    override fun createReport(report: Report): Report {
        return mapper.toModel(jpa.save(mapper.toEntity(report)))
    }

    override fun createReports(reports: MutableList<Report>): MutableList<Report> {
        return mapper.toModels(jpa.saveAll(mapper.toEntities(reports)))
    }

    override fun getStartingReport(): Report? {
        val entity = jpa.findFirstByStartIsTrue() ?: return null
        return mapper.toModel(entity)
    }

    override fun getNonStartingReports(endDate: Date?): MutableList<Report> {
        if (endDate != null) {
            return mapper.toModels(jpa.findByStartIsFalseAndReportMonthLessThanEqual(endDate))
        }

        return mapper.toModels(jpa.findByStartIsFalse())
    }

    override fun deleteAllReportsAfter(endDate: Date): Long {
        return jpa.deleteByReportMonthGreaterThan(endDate)
    }

    override fun deleteAllReportsAfterOrAtDate(endDate: Date): Long {
        return jpa.deleteByReportMonthGreaterThanEqual(endDate)
    }


    override fun deleteAllReportsBefore(endDate: Date): Long {
        return jpa.deleteByReportMonthLessThanEqual(endDate)
    }


}