package org.micord.controller;

import org.micord.enums.ConfigType;
import org.micord.models.requests.RequestParameters;
import org.micord.service.ApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * REST Controller for API operations.
 */
@RestController
@RequestMapping("/api")
public class ApiController {

  private static final Logger logger = LoggerFactory.getLogger(ApiController.class);

  @Autowired
  private ApiService apiService;

  @PostMapping("/removeMilitaryDraftNotices")
  public ResponseEntity<?> removeMilitaryDraftNotices(@RequestBody RequestParameters request) throws SQLException, FileNotFoundException {
    List<String> ids = request.getIds();

    logger.debug("Starting removeMilitaryDraftNotices process for ids: {}", ids);
    apiService.process(ConfigType.REMOVE_MILITARY_DRAFT_NOTICES, request);
    logger.debug("Finished removeMilitaryDraftNotices process for ids: {}", ids);

    return ResponseEntity.ok("Операция \"Удаление повесток\" завершена успешно.");
  }

  @PostMapping("/deleteFiles")
  public ResponseEntity<?> deleteFiles(@RequestBody List<String> ids) throws FileNotFoundException, SQLException {

    apiService.process(ConfigType.DELETE_FILES, ids);

    return ResponseEntity.ok("Операция \"Удаление файлов\" завершена успешно.");
  }

  @PostMapping("/block")
  public ResponseEntity<?> block(@RequestBody List<String> ids) throws SQLException, FileNotFoundException {

    logger.debug("Starting block process for ids: {}", ids);
    apiService.process(ConfigType.BLOCK, ids);
    logger.debug("Finished block process for ids: {}", ids);

    return ResponseEntity.ok("Операция \"Блокировка\" завершена успешно.");
  }


  @PostMapping("/unblock")
  public ResponseEntity<?> unblock(@RequestBody List<String> ids) throws SQLException, FileNotFoundException {

    logger.debug("Starting unblock process for ids: {}", ids);
    apiService.process(ConfigType.UNBLOCK, ids);
    logger.debug("Finished unblock process for ids: {}", ids);

    return ResponseEntity.ok("Операция \"Разблокировка\" завершена успешно.");
  }


  @PostMapping("/removeFromSystem")
  public ResponseEntity<?> removeFromSystem(@RequestBody List<String> ids) throws SQLException, FileNotFoundException {

    logger.debug("Starting removeFromSystem process for ids: {}", ids);
    apiService.process(ConfigType.REMOVE_FROM_SYSTEM, ids);
    logger.debug("Finished removeFromSystem process for ids: {}", ids);

    return ResponseEntity.ok("Операция \"Удаление данных по гражданину\" завершена успешно.");
  }


  @PostMapping("/removeFromCallList")
  public ResponseEntity<?> removeFromCallList(@RequestBody List<String> ids) throws SQLException, FileNotFoundException {

    logger.debug("Starting removeFromCallList process for ids: {}", ids);
    apiService.process(ConfigType.REMOVE_FROM_CALL_LIST, ids);
    logger.debug("Finished removeFromCallList process for ids: {}", ids);

    return ResponseEntity.ok("Операция \"Удаление из списков на вызов\" завершена успешно.");
  }


  @PostMapping("/downloadCSV")
  public ResponseEntity<Resource> downloadCSV(@RequestBody RequestParameters request) throws IOException, SQLException {
    logger.debug("Starting downloadCSV process for request: {}", request.getType());

    File downloadFile = apiService.download(ConfigType.DOWNLOAD_CSV, request);
    InputStreamResource resource = new InputStreamResource(new FileInputStream(downloadFile));

    logger.debug("Finished downloadCSV process for request: {}. Sending to user...", request.getType());

    // Determine content type based on file extension
    String fileName = downloadFile.getName();
    MediaType contentType;
    if (fileName.toLowerCase().endsWith(".zip")) {
      contentType = MediaType.APPLICATION_OCTET_STREAM;
    } else {
      contentType = MediaType.parseMediaType("text/csv; charset=UTF-8");
    }

    ResponseEntity.BodyBuilder response = ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
        .contentType(contentType)
        .contentLength(downloadFile.length());

    // Only add content encoding for CSV files
    if (!fileName.endsWith(".zip")) {
      response.header(HttpHeaders.CONTENT_ENCODING, "UTF-8");
    }

    return response.body(resource);
  }


  @GetMapping("/listDownloadTypes")
  public ResponseEntity<List<String>> listDownloadTypes() throws FileNotFoundException {
    logger.debug("Fetching list of download types...");

    List<String> downloadCSVTypes = apiService.getDownloadTypes(ConfigType.DOWNLOAD_CSV);

    logger.debug("Successfully retrieved download types");
    return ResponseEntity.ok(downloadCSVTypes);
  }
}
