package com.rtlabs.orders;

import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/orders")
public class OrderExportController {

  private final OrderExportService exportService;
  private final DownloadAuditService downloadAuditService;

  public OrderExportController(OrderExportService exportService,
                               DownloadAuditService downloadAuditService) {
    this.exportService = exportService;
    this.downloadAuditService = downloadAuditService;
  }

  @GetMapping("/{orderId}/export")
  public ResponseEntity<Resource> exportOrder(
      @PathVariable Long orderId,
      @AuthenticationPrincipal AppUser currentUser) {

    Resource csv = exportService.renderCsv(orderId);

    downloadAuditService.log(currentUser.getUsername(), orderId);
    return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"order-" + orderId + ".csv\"")
        .body(csv);
  }
}
