package controllers

import (
	"crypto/rand"
	"encoding/hex"
	"io"
	"net/http"
	"os"
	"path/filepath"

	"github.com/gin-gonic/gin"
)

func generateID() (string, error) {
	bytes := make([]byte, 16)
	_, err := rand.Read(bytes)
	return hex.EncodeToString(bytes), err
}

func HandleFileUpload(c *gin.Context) {
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "No file provided"})
		return
	}
	defer file.Close()

	fileID, err := generateID()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate file ID"})
		return
	}

	fileDir := filepath.Join("./uploads", fileID)
	if err := os.MkdirAll(fileDir, 0755); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create file directory"})
		return
	}

	out, err := os.Create(filepath.Join(fileDir, header.Filename))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create file"})
		return
	}
	defer out.Close()

	if _, err = io.Copy(out, file); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save file"})
		return
	}

	baseURL := os.Getenv("BASE_URL")
	if baseURL == "" {
		baseURL = "http://localhost:8080"
	}

	c.JSON(http.StatusOK, gin.H{
		"message":  "File uploaded successfully",
		"id":       fileID,
		"filename": header.Filename,
		"size":     header.Size,
		"url":      baseURL + "/uploads/" + fileID + "/" + header.Filename,
	})
}
