package es.tatvil.taiageweb.controlador;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/api/temas")
public class TemaController {

    @GetMapping("/**")
    public ResponseEntity<String> getTema(HttpServletRequest request) throws IOException {
        String uri = request.getRequestURI();
        String path = uri.substring("/api/temas/".length());

        // Prevenir path traversal
        if (path.contains("..") || path.contains("//") || path.startsWith("/")) {
            return ResponseEntity.badRequest().build();
        }

        ClassPathResource resource = new ClassPathResource("temas/" + path);
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        String content = new String(resource.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
        return ResponseEntity.ok()
                .contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
                .body(content);
    }
}
