package com.oguerreiro.resilient.repository;

import java.util.List;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.oguerreiro.resilient.domain.DashboardComponent;
import com.oguerreiro.resilient.domain.DashboardComponentDetailValue;
import com.oguerreiro.resilient.domain.enumeration.DashboardComponentView;

/**
 * Spring Data JPA repository for the DashboardComponent entity.
 */
@SuppressWarnings("unused")
@Repository
public interface DashboardComponentRepository extends ResilientJpaRepository<DashboardComponent, Long> {
  @Query("""
      SELECT new com.oguerreiro.resilient.domain.DashboardComponentDetailValue(d, tdc, o.owner, o.value)
      FROM   DashboardComponentDetail d
                LEFT JOIN OutputData o ON d.variable=o.variable AND o.periodVersion.id=:periodVersionId
                LEFT JOIN FETCH d.targetDashboardComponent tdc
      WHERE d.dashboardComponent.id = :dashboardComponentId
            AND (:organizationId IS NULL OR o.owner.id = :organizationId)
      ORDER BY d.indexOrder, d.name
      """)
  List<DashboardComponentDetailValue> loadAllDashboardComponentDetailValues(
      @Param("organizationId") Long organizationId, @Param("periodVersionId") Long periodVersionId,
      @Param("dashboardComponentId") Long dashboardComponentId);

  @Query("""
      SELECT c
      FROM   DashboardComponent c
      WHERE  c.isActive = true
      """)
  List<DashboardComponent> findAllActive();

  @Query("""
      SELECT c
      FROM   DashboardComponent c
      WHERE  c.isActive = true
             AND c.view = :dashboardComponentView
      """)
  List<DashboardComponent> findAllActiveForView(
      @Param("dashboardComponentView") DashboardComponentView dashboardComponentView);
}
