package ru.soune.nocopy.dto.search;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Data;
import ru.soune.nocopy.entity.search.GlobalSearchTask;

import java.time.format.DateTimeFormatter;
import java.util.List;

@Data
@Builder
public class GlobalSearchStatisticsResponse {

    @JsonProperty("total_searches")
    private long totalSearches;

    @JsonProperty("searches_by_status")
    private StatusCountDto searchesByStatus;

    @JsonProperty("recent_searches")
    private List<SearchStatDto> recentSearches;

    @Data
    @Builder
    public static class StatusCountDto {
        @JsonProperty("processing")
        private long processing;

        @JsonProperty("completed")
        private long completed;

        @JsonProperty("failed")
        private long failed;

        @JsonProperty("total")
        private long total;
    }

    @Data
    @Builder
    public static class SearchStatDto {
        @JsonProperty("task_id")
        private String taskId;

        @JsonProperty("search_type")
        private String searchType;

        @JsonProperty("status")
        private String status;

        @JsonProperty("total_files")
        private Integer totalFiles;

        @JsonProperty("violations_found")
        private long violationsFound;

        @JsonProperty("created_at")
        private String createdAt;

        @JsonProperty("duration_seconds")
        private Long durationSeconds;

        @JsonProperty("file_ids")
        private List<String> fileIds;

        public static SearchStatDto fromEntity(GlobalSearchTask task, long violationsCount, List<String> fileIds ) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            Long duration = null;
            if (task.getUpdatedAt() != null && task.getCreatedAt() != null) {
                duration = java.time.Duration.between(task.getCreatedAt(), task.getUpdatedAt()).getSeconds();
            }

            return SearchStatDto.builder()
                    .taskId(task.getTaskId())
                    .searchType(task.getSearchType())
                    .status(task.getStatus())
                    .totalFiles(task.getTotalFiles())
                    .violationsFound(violationsCount)
                    .fileIds(fileIds)
                    .createdAt(task.getCreatedAt() != null ? task.getCreatedAt().format(formatter) : null)
                    .durationSeconds(duration)
                    .build();
        }
    }
}
