package com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository;

import java.time.OffsetDateTime;
import java.util.List;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

import com.iqser.red.service.persistence.management.v1.processor.entity.audit.AuditEntity;
import com.iqser.red.service.persistence.service.v1.api.shared.model.audit.CategoryModel;

public interface AuditRepository extends JpaRepository<AuditEntity, Long>, JpaSpecificationExecutor<AuditEntity> {

    static Specification<AuditEntity> categoryMatches(String category) {

        return (audit, cq, cb) -> cb.equal(audit.get("category"), category);
    }


    static Specification<AuditEntity> userMatches(String user) {

        return (audit, cq, cb) -> cb.equal(audit.get("userId"), user);
    }


    static Specification<AuditEntity> objectIdMatches(String objectId) {

        return (audit, cq, cb) -> cb.equal(audit.get("objectId"), objectId);
    }


    static Specification<AuditEntity> dateBetween(OffsetDateTime start, OffsetDateTime end) {

        return (audit, cq, cb) -> cb.between(audit.get("recordDate"), start, end);
    }


    @Query("SELECT new com.iqser.red.service.persistence.service.v1.api.shared.model.audit.CategoryModel(a.category, count(a)) FROM AuditEntity a GROUP BY a.category")
    List<CategoryModel> findCategories();

}
