package com.spring.domain.schedule.dto;

import java.time.LocalDateTime;

import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.validation.constraints.NotNull;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.format.annotation.DateTimeFormat;

import com.spring.common.jpa.SpecBuilder;
import com.spring.domain.schedule.entity.BatchJobExecution;
import com.spring.domain.schedule.entity.BatchJobInstance;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class FindJobHistoryRequest {

    @NotNull(message = "시작일자는 필수값 입니다.")
    @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
    private final LocalDateTime fromDate;

    @NotNull(message = "종료일자는 필수값 입니다.")
    @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
    private final LocalDateTime toDate;

    private final String jobName;

    public Specification<BatchJobExecution> betweenCreateTime() {
        return (root, query, builder) -> builder.between(root.get("createTime"), fromDate, toDate);
    }

    public Specification<BatchJobExecution> equalJobName() {
        return (root, query, builder) -> {
            Join<BatchJobExecution, BatchJobInstance> join = root.join("jobInstance", JoinType.INNER);
            return builder.equal(join.get("jobName"), jobName);
        };
    }

    public Specification<BatchJobExecution> toPredicate() {
        return SpecBuilder.builder(BatchJobExecution.class)
          .and(betweenCreateTime())
          .ifHasText(jobName, equalJobName())
          .toSpec();
    }

}
