package com.kamco.cd.training.postgres.repository.train;

import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;

import com.kamco.cd.training.common.enums.TrainStatusType;
import com.kamco.cd.training.postgres.entity.ModelMetricsTestEntity;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.util.List;
import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport;
import org.springframework.jdbc.core.JdbcTemplate;

public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
    implements ModelTestMetricsJobRepositoryCustom {

  private final JPAQueryFactory queryFactory;
  private final JdbcTemplate jdbcTemplate;

  public ModelTestMetricsJobRepositoryImpl(
      JPAQueryFactory queryFactory, JdbcTemplate jdbcTemplate) {
    super(ModelMetricsTestEntity.class);
    this.queryFactory = queryFactory;
    this.jdbcTemplate = jdbcTemplate;
  }

  @Override
  public void updateModelMetricsTrainSaveYn(Long modelId, String stepNo) {
    queryFactory
        .update(modelMasterEntity)
        .set(
            stepNo.equals("step1")
                ? modelMasterEntity.step1MetricSaveYn
                : modelMasterEntity.step2MetricSaveYn,
            true)
        .where(modelMasterEntity.id.eq(modelId))
        .execute();
  }

  @Override
  public List<Long> getTestMetricSaveNotYetModelIds() {
    return queryFactory
        .select(modelMasterEntity.id)
        .from(modelMasterEntity)
        .where(
            modelMasterEntity.step2EndDttm.isNotNull(),
            modelMasterEntity.step2State.eq(TrainStatusType.COMPLETED.getId()),
            modelMasterEntity
                .step2MetricSaveYn
                .isNull()
                .or(modelMasterEntity.step2MetricSaveYn.isFalse()))
        .fetch();
  }

  @Override
  public void insertModelMetricsTest(List<Object[]> batchArgs) {
    String sql =
        """
          insert into tb_model_metrics_test
          (model_id, model, tp, fp, fn, precisions, recall, f1_score, accuracy, iou,
           detection_count, gt_count
           )
          values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      """;

    jdbcTemplate.batchUpdate(sql, batchArgs);
  }
}
