package com.kamco.cd.kamcoback.postgres.repository.model;

import static com.kamco.cd.kamcoback.postgres.entity.QModelMgmtEntity.modelMgmtEntity;
import static com.kamco.cd.kamcoback.postgres.entity.QModelResultMetricEntity.modelResultMetricEntity;

import com.kamco.cd.kamcoback.model.dto.ModelMgmtDto;
import com.kamco.cd.kamcoback.postgres.QuerydslOrderUtil;
import com.kamco.cd.kamcoback.postgres.entity.ModelMgmtEntity;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.core.types.dsl.StringExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport;

public class ModelMgmtRepositoryImpl extends QuerydslRepositorySupport
    implements ModelMgmtRepositoryCustom {

  private final JPAQueryFactory queryFactory;
  private final StringExpression NULL_STRING = Expressions.stringTemplate("cast(null as text)");

  public ModelMgmtRepositoryImpl(JPAQueryFactory queryFactory) {
    super(ModelMgmtEntity.class);
    this.queryFactory = queryFactory;
  }

  @Override
  public Page<ModelMgmtDto.ModelList> findModelMgmtList(
      ModelMgmtDto.searchReq searchReq,
      LocalDate startDate,
      LocalDate endDate,
      String modelType,
      String searchVal) {
    Pageable pageable = searchReq.toPageable();
    Sort sort = pageable.getSort();
    String property = "createCompleteDttm"; // 기본으로 생성완료일 기준

    Map<String, Expression<?>> sortColumnMap =
        Map.of(
            "createCompleteDttm", modelMgmtEntity.createCompleteDttm,
            "recentUseDttm", modelMgmtEntity.recentUseDttm);

    if (sort.isSorted()) {
      Sort.Order order = sort.iterator().next();
      property = order.getProperty();
    }

    Expression<?> sortColumn = sortColumnMap.get(property);

    List<ModelMgmtDto.ModelList> foundContent =
        queryFactory
            .select(
                Projections.constructor(
                    ModelMgmtDto.ModelList.class,
                    Expressions.numberTemplate(
                        Integer.class, "row_number() over(order by {0} desc)", sortColumn),
                    Expressions.stringTemplate(
                            "concat({0}, {1}, {2}, {3}, {4})",
                            modelMgmtEntity.modelVer,
                            ".",
                            modelMgmtEntity.hyperVer,
                            ".",
                            modelMgmtEntity.epochVer)
                        .as("modelVer"),
                    modelMgmtEntity.dockerFileNm,
                    modelMgmtEntity.modelVer.as("modelType"),
                    Expressions.stringTemplate(
                        "to_char({0}, 'YYYY-MM-DD')", modelMgmtEntity.createCompleteDttm),
                    Expressions.stringTemplate(
                        "to_char({0}, 'YYYY-MM-DD')", modelMgmtEntity.recentUseDttm),
                    roundNumericToPercent(modelResultMetricEntity.f1Score),
                    roundNumericToPercent(modelResultMetricEntity.precision),
                    roundNumericToPercent(modelResultMetricEntity.recall),
                    roundNumericToPercent(modelResultMetricEntity.loss),
                    roundNumericToPercent(modelResultMetricEntity.iou),
                    modelMgmtEntity.deleted))
            .from(modelMgmtEntity)
            .innerJoin(modelResultMetricEntity)
            .on(modelMgmtEntity.modelUid.longValue().eq(modelResultMetricEntity.modelUid))
            .where(
                eventEndedAtBetween(startDate, endDate, property),
                searchModelVersion(modelType, searchVal))
            .offset(pageable.getOffset())
            .limit(pageable.getPageSize())
            .orderBy(
                QuerydslOrderUtil.getOrderSpecifiers(
                    pageable, ModelMgmtEntity.class, "modelMgmtEntity"))
            .fetch();

    Long countQuery =
        queryFactory
            .select(modelMgmtEntity.modelUid.count())
            .from(modelMgmtEntity)
            .where(
                eventEndedAtBetween(startDate, endDate, property),
                searchModelVersion(modelType, searchVal))
            .fetchOne();

    return new PageImpl<>(foundContent, pageable, countQuery);
  }

  private BooleanExpression eventEndedAtBetween(
      LocalDate startDate, LocalDate endDate, String sortColumn) {
    if (Objects.isNull(startDate) || Objects.isNull(endDate)) {
      return null;
    }
    ZoneId zone = ZoneId.systemDefault();
    LocalDateTime startDateTime = startDate.atStartOfDay();
    LocalDateTime endDateTime = endDate.plusDays(1).atStartOfDay();

    if (sortColumn.equals("createCompleteDttm")) {
      return modelMgmtEntity
          .createCompleteDttm
          .goe(startDateTime.atZone(zone))
          .and(modelMgmtEntity.createCompleteDttm.lt(endDateTime.atZone(zone)));
    } else {
      return modelMgmtEntity
          .recentUseDttm
          .goe(startDateTime.atZone(zone))
          .and(modelMgmtEntity.recentUseDttm.lt(endDateTime.atZone(zone)));
    }
  }

  private BooleanBuilder searchModelVersion(String modelType, String searchVal) {
    BooleanBuilder builder = new BooleanBuilder();

    if (Objects.nonNull(modelType)) {
      builder.and(modelMgmtEntity.modelVer.eq(modelType));
    }

    if (Objects.nonNull(searchVal)) {
      builder.and(modelMgmtEntity.dockerFileNm.likeIgnoreCase("%" + searchVal + "%"));
    }

    return builder;
  }

  private Expression<BigDecimal> roundNumericToPercent(NumberPath<Double> ratio) {
    return Expressions.numberTemplate(BigDecimal.class, "function('round', {0} * 100, 2)", ratio);
  }
}
