package controllers

import (
	"fmt"
	"net/http"
	"os"
	"path/filepath"

	"fitra-backend/utils"

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

func HandleFileDownload(c *gin.Context) {
	fileID, filename := c.Param("fileID"), c.Param("filename")

	if fileID == "" || filename == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "File ID and filename are required"})
		return
	}

	filePath := filepath.Join("./uploads", fileID, filename)

	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		c.JSON(http.StatusNotFound, gin.H{"error": "File not found"})
		return
	}

	// Send analytics event
	properties := fmt.Sprintf(`{"filename": "%s"}`, filename)
	_ = utils.SendCustomEvent("file_download", "/api/download/"+fileID+"/"+filename, properties)

	c.Header("Content-Description", "File Transfer")
	c.Header("Content-Transfer-Encoding", "binary")
	c.Header("Content-Disposition", "attachment; filename="+filename)
	c.Header("Content-Type", "application/octet-stream")
	c.File(filePath)
}
