package controllers

import (
	"canguidev/shelfy/internal/models"
	"errors"
	"net/http"
	"os"
	"strings"

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

func CreateSavePath(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Content-Type", "application/json")

		var pathDownload models.PathDownload
		if err := c.ShouldBindJSON(&pathDownload); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
			return
		}

		if pathDownload.PathName == "" {
			c.JSON(http.StatusBadRequest, gin.H{"error": "PathName cannot be empty"})
			return
		}

		fullPath := "/app/upload/" + pathDownload.PathName
		if _, err := os.Stat(fullPath); err == nil {
			c.JSON(http.StatusConflict, gin.H{"error": "Path already exists"})
			return
		}

		if err := os.MkdirAll(fullPath, 0755); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create directory"})
			return
		}

		pathDownload.Path = fullPath
		if err := db.Create(&pathDownload).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save path"})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"message": "Path created successfully",
			"data":    pathDownload,
		})
	}
}

func ReadAllSavePath(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Content-Type", "application/json")

		var paths []models.PathDownload
		if err := db.Find(&paths).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve paths"})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"message": "Paths retrieved successfully",
			"data":    paths,
		})
	}
}

// UpdateSavePath met à jour un chemin enregistré et renomme le dossier
func UpdateSavePath(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Content-Type", "application/json")
		id := c.Param("id")

		var pathDownload models.PathDownload
		if err := c.ShouldBindJSON(&pathDownload); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON format"})
			return
		}

		var existingPath models.PathDownload
		if err := db.First(&existingPath, "id = ?", id).Error; err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "Path not found"})
			return
		}

		oldFullPath := "/app/upload/" + existingPath.PathName
		newFullPath := "/app/upload/" + pathDownload.PathName

		if oldFullPath != newFullPath {
			if err := os.Rename(oldFullPath, newFullPath); err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to rename directory"})
				return
			}
		}

		existingPath.PathName = pathDownload.PathName
		existingPath.Path = newFullPath

		if err := db.Save(&existingPath).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update path"})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"message": "Path updated successfully",
			"data":    existingPath,
		})
	}
}


// DeleteSavePath supprime un chemin et son dossier
func DeleteSavePath(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		id := c.Param("id")

		var pathDownload models.PathDownload
		if err := db.First(&pathDownload, "id = ?", id).Error; err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "Path not found"})
			return
		}

		fullPath := "/app/upload/" + pathDownload.PathName
		if err := os.RemoveAll(fullPath); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete directory"})
			return
		}

		if err := db.Delete(&pathDownload).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete path"})
			return
		}

		c.JSON(http.StatusOK, gin.H{"message": "Path deleted successfully"})
	}
}

// IsPathValid vérifie si un chemin est valide (nom et existence)
func IsPathValid(pathName string) error {
	if pathName == "" {
		return errors.New("PathName cannot be empty")
	}
	if strings.Contains(pathName, "/") || strings.Contains(pathName, "\\") {
		return errors.New("PathName cannot contain '/' or '\\'")
	}
	fullPath := "/app/upload/" + pathName
	if _, err := os.Stat(fullPath); err == nil {
		return errors.New("Path already exists")
	}
	return nil
}

// PathValidationHandler vérifie la validité du chemin (POST uniquement)
func PathValidationHandler(c *gin.Context) {
	if c.Request.Method != http.MethodPost {
		c.JSON(http.StatusMethodNotAllowed, gin.H{"error": "Invalid request method"})
		return
	}

	var requestBody struct {
		PathName string `json:"pathName"`
	}

	if err := c.ShouldBindJSON(&requestBody); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	err := IsPathValid(requestBody.PathName)

	response := gin.H{
		"pathName": requestBody.PathName,
		"status":   "valid",
	}

	if err != nil {
		response["status"] = "invalid"
		response["error"] = err.Error()
		c.JSON(http.StatusBadRequest, response)
		return
	}

	c.JSON(http.StatusOK, response)
}

