package ru.soune.nocopy.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.soune.nocopy.dto.search.GlobalSearchStartRequest;
import ru.soune.nocopy.dto.search.GlobalSearchStartResponse;
import ru.soune.nocopy.dto.search.GlobalSearchStatusResponse;
import ru.soune.nocopy.dto.violation.FileViolationSummaryDTO;
import ru.soune.nocopy.dto.violation.ViolationRequest;
import ru.soune.nocopy.entity.file.FileEntity;
import ru.soune.nocopy.entity.search.GlobalSearchTask;
import ru.soune.nocopy.entity.search.SearchStatus;
import ru.soune.nocopy.repository.GlobalSearchTaskRepository;
import ru.soune.nocopy.service.search.GlobalSearchService;
import ru.soune.nocopy.service.violation.ViolationService;

import java.util.*;

@Slf4j
@RestController
@RequestMapping("/api/v1/global-search")
@RequiredArgsConstructor
public class GlobalSearchController {

    private final GlobalSearchService globalSearchService;

    private final GlobalSearchTaskRepository searchTaskRepository;

    private final ViolationService violationService;

    private final HttpServletRequest httpServletRequest;

    @PostMapping("/start")
    public ResponseEntity<?> startSearch(
            @RequestBody GlobalSearchStartRequest request) {
        GlobalSearchStartResponse response = new GlobalSearchStartResponse();

        Long userId = (Long) httpServletRequest.getAttribute("userId");

        List<FileEntity> filesToProcess = globalSearchService.getFilesToProcess(request, userId);

        if (filesToProcess.isEmpty()) return ResponseEntity.ok().body("Files for search not found");

        String taskId = globalSearchService.startSearch(request, userId, filesToProcess);

        response.setTaskId(taskId);
        response.setStatus(SearchStatus.ACCEPTED.name());
        response.setTotalFiles(filesToProcess.size());

        return ResponseEntity.ok(response);
    }

    @GetMapping("/actual-task")
    public ResponseEntity<?> getStatus() {
        Optional<GlobalSearchTask> taskOptional;

        Long userId = (Long) httpServletRequest.getAttribute("userId");

        taskOptional = searchTaskRepository.findByUserIdAndStatus(userId,
                "PROCESSING");

        if (taskOptional.isEmpty()) return ResponseEntity.ok().body("Task not found");

        return ResponseEntity.ok(taskOptional.get());
    }

    @GetMapping("/violation-summary")
    public ResponseEntity<?> getSummary() {
        List<FileViolationSummaryDTO> fileViolationsSummary;

        Long userId = (Long) httpServletRequest.getAttribute("userId");

        fileViolationsSummary = violationService.getFileViolationsSummary(userId);

        if (fileViolationsSummary.isEmpty()) return ResponseEntity.ok().body("Violations summary not found");

        return ResponseEntity.ok(fileViolationsSummary);
    }


    @PostMapping("/violation-summary-with-files")
    public ResponseEntity<?> getViolations(@RequestBody ViolationRequest request) {
        Long userId = (Long) httpServletRequest.getAttribute("userId");
        Page<FileViolationSummaryDTO> result = violationService.getFileViolationsSummary(
                userId, request.getFileName(), request.getSortDirection(),
                request.getPage(), request.getSize(), request.getStartDate(), request.getEndDate());

        return ResponseEntity.ok(result);
    }

    @GetMapping("/status/{taskId}")
    public ResponseEntity<?> getStatus(@PathVariable String taskId) {
        GlobalSearchStatusResponse response;
        Long userId = (Long) httpServletRequest.getAttribute("userId");

        Optional<GlobalSearchTask> taskOptional = searchTaskRepository.findByTaskIdAndUserId(taskId, userId);

        if (taskOptional.isEmpty()) return ResponseEntity.ok().body("Task not found");

        GlobalSearchTask task = taskOptional.orElseThrow();

        int progress = task.getTotalFiles() > 0 ? task.getProcessedFiles() * 100 / task.getTotalFiles() : 0;

        response = new GlobalSearchStatusResponse();
        response.setTaskId(taskId);
        response.setStatus(task.getStatus());
        response.setProgress(progress);


        return ResponseEntity.ok(response);
    }
}
