package kz.konturai.parser.controller;

import kz.konturai.parser.service.MinIOService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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;

import java.io.InputStream;

/**
 * Controller for public access to marketing images and videos at the root level.
 * This handles requests to https://api.konturai.kz/image_*.png or video_*.mp4.
 */
@RestController
@RequestMapping("/api/marketing")
@RequiredArgsConstructor
@Slf4j
public class PublicAssetController {

    private final MinIOService minIOService;

    /**
     * Serves images that start with "image_" and end with ".png" from the root.
     * Example: https://api.konturai.kz/image_1772616225367_1567876836.png
     */
    @GetMapping("/{filename:image_.+\\.png}")
    public ResponseEntity<byte[]> getPublicImage(@PathVariable String filename) {
        log.info("[PublicAsset] Access request for image: {}", filename);
        try {
            if (!minIOService.fileExists(filename)) {
                return ResponseEntity.notFound().build();
            }

            try (InputStream is = minIOService.downloadFile(filename)) {
                byte[] bytes = is.readAllBytes();
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE)
                        .header(HttpHeaders.CACHE_CONTROL, "public, max-age=3600")
                        .body(bytes);
            }
        } catch (Exception e) {
            log.error("[PublicAsset] Failed to serve public image {}: {}", filename, e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * Serves videos that start with "video_" and end with ".mp4" from the root.
     * Example: https://api.konturai.kz/video_1772616225367_1567876836.mp4
     */
    @GetMapping("/{filename:video_.+\\.mp4}")
    public ResponseEntity<Resource> getPublicVideo(@PathVariable String filename) {
        log.info("[PublicAsset] Access request for video: {}", filename);
        try {
            if (!minIOService.fileExists(filename)) {
                return ResponseEntity.notFound().build();
            }

            InputStream is = minIOService.downloadFile(filename);
            InputStreamResource resource = new InputStreamResource(is);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, "video/mp4")
                    .header(HttpHeaders.CACHE_CONTROL, "public, max-age=3600")
                    .body(resource);
        } catch (Exception e) {
            log.error("[PublicAsset] Failed to serve public video {}: {}", filename, e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
