package com.realnet.Heplers;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

@Service
public class FileHelper {

	public void createFile(String folderPath, String pageName, String htmlContent) throws IOException {

		File file = new File(folderPath + "/" + pageName);

		// Ensure directory exists
		File parentDir = file.getParentFile();
		if (!parentDir.exists()) {

			parentDir.mkdirs();
		}

		// Create new file
		if (!file.exists()) {
			file.createNewFile();
		}

		try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
			writer.write(htmlContent);

		}

		System.out.println("✅ File created: " + file.getAbsolutePath());

	}

	public ResponseEntity<?> readFile(String filepath, String filename) {
		File file = new File(filepath + "/" + filename + ".html");
		System.out.println(" reading file : " + file);
		if (!file.exists()) {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).body("❌ File not found: " + file.getAbsolutePath());
		}

		try {
			String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);

			return ResponseEntity.ok(content);
		} catch (IOException e) {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
					.body("Error reading file: " + e.getMessage());
		}
	}
}
