package controllers

import (
	"fmt"
	database "goFiber/database/config"
	"goFiber/database/models"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"time"

	"github.com/gofiber/fiber/v3"
	"gorm.io/gorm"
)

// GetSetting godoc
// @Summary Get site settings
// @Tags Setting
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Failure 404 {object} map[string]string
// @Router /api/v1/setting [get]
func GetSetting(c fiber.Ctx) error {
	var setting models.Setting
	// Arkaplanda tek bir aktif ayar varsayıyoruz veya en son ekleneni/güncelleneni
	if err := database.DB.Where("is_active = ?", true).Last(&setting).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": "no active setting found"})
		}
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "database error"})
	}
	return c.JSON(setting)
}

// CreateSetting godoc
// @Summary Create new site setting (admin only)
// @Tags Setting
// @Accept mpfd
// @Produce json
// @Security BearerAuth
// @Param title formData string true "Title"
// @Param meta_title formData string true "Meta Title"
// @Param meta_description formData string true "Meta Description"
// @Param phone formData string true "Phone"
// @Param url formData string true "URL"
// @Param email formData string true "Email"
// @Param facebook formData string false "Facebook"
// @Param x formData string false "X"
// @Param instagram formData string false "Instagram"
// @Param whatsapp formData string false "Whatsapp"
// @Param pinterest formData string false "Pinterest"
// @Param linkedin formData string false "Linkedin"
// @Param slogan formData string false "Slogan"
// @Param address formData string false "Address"
// @Param copyright formData string false "Copyright"
// @Param map_embed formData string false "Map Embed"
// @Param is_active formData boolean false "Is Active"
// @Param w_logo formData file false "White Logo"
// @Param b_logo formData file false "Black Logo"
// @Success 201 {object} map[string]interface{}
// @Failure 400 {object} map[string]string
// @Router /api/v1/setting [post]
func CreateSetting(c fiber.Ctx) error {
	var setting models.Setting
	if err := c.Bind().Body(&setting); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request body"})
	}

	// White Logo upload
	if file, err := c.FormFile("w_logo"); err == nil {
		if _, err := os.Stat("./uploads/settings"); os.IsNotExist(err) {
			os.MkdirAll("./uploads/settings", 0755)
		}
		filename := fmt.Sprintf("w_%d_%s", time.Now().Unix(), file.Filename)
		filePath := filepath.Join("./uploads/settings", filename)
		if err := c.SaveFile(file, filePath); err != nil {
			return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to save w_logo"})
		}
		setting.WLogo = "/uploads/settings/" + filename
	}

	// Black Logo upload
	if file, err := c.FormFile("b_logo"); err == nil {
		if _, err := os.Stat("./uploads/settings"); os.IsNotExist(err) {
			os.MkdirAll("./uploads/settings", 0755)
		}
		filename := fmt.Sprintf("b_%d_%s", time.Now().Unix(), file.Filename)
		filePath := filepath.Join("./uploads/settings", filename)
		if err := c.SaveFile(file, filePath); err != nil {
			return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to save b_logo"})
		}
		setting.BLogo = "/uploads/settings/" + filename
	}

	// Eğer sadece bir aktif ayar olacaksa, diğerlerini pasife çekebiliriz
	if setting.IsActive {
		database.DB.Model(&models.Setting{}).Where("is_active = ?", true).Update("is_active", false)
	}

	if err := database.DB.Create(&setting).Error; err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "setting could not be created"})
	}

	return c.Status(http.StatusCreated).JSON(setting)
}

// UpdateSetting godoc
// @Summary Update site setting (admin only)
// @Tags Setting
// @Accept mpfd
// @Produce json
// @Security BearerAuth
// @Param id path int true "Setting ID"
// @Param title formData string false "Title"
// @Param meta_title formData string false "Meta Title"
// @Param meta_description formData string false "Meta Description"
// @Param phone formData string false "Phone"
// @Param url formData string false "URL"
// @Param email formData string false "Email"
// @Param facebook formData string false "Facebook"
// @Param x formData string false "X"
// @Param instagram formData string false "Instagram"
// @Param whatsapp formData string false "Whatsapp"
// @Param pinterest formData string false "Pinterest"
// @Param linkedin formData string false "Linkedin"
// @Param slogan formData string false "Slogan"
// @Param address formData string false "Address"
// @Param copyright formData string false "Copyright"
// @Param map_embed formData string false "Map Embed"
// @Param is_active formData boolean false "Is Active"
// @Param w_logo formData file false "White Logo"
// @Param b_logo formData file false "Black Logo"
// @Success 200 {object} map[string]interface{}
// @Failure 400 {object} map[string]string
// @Failure 404 {object} map[string]string
// @Router /api/v1/setting/{id} [put]
func UpdateSetting(c fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid id"})
	}

	var setting models.Setting
	if err := database.DB.First(&setting, id).Error; err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": "setting not found"})
	}

	var updateData models.Setting
	if err := c.Bind().Body(&updateData); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request body"})
	}

	// White Logo upload
	if file, err := c.FormFile("w_logo"); err == nil {
		if _, err := os.Stat("./uploads/settings"); os.IsNotExist(err) {
			os.MkdirAll("./uploads/settings", 0755)
		}
		filename := fmt.Sprintf("w_%d_%s", time.Now().Unix(), file.Filename)
		filePath := filepath.Join("./uploads/settings", filename)
		if err := c.SaveFile(file, filePath); err != nil {
			return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to save w_logo"})
		}
		updateData.WLogo = "/uploads/settings/" + filename
	}

	// Black Logo upload
	if file, err := c.FormFile("b_logo"); err == nil {
		if _, err := os.Stat("./uploads/settings"); os.IsNotExist(err) {
			os.MkdirAll("./uploads/settings", 0755)
		}
		filename := fmt.Sprintf("b_%d_%s", time.Now().Unix(), file.Filename)
		filePath := filepath.Join("./uploads/settings", filename)
		if err := c.SaveFile(file, filePath); err != nil {
			return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to save b_logo"})
		}
		updateData.BLogo = "/uploads/settings/" + filename
	}

	// Eğer bu ayar aktif yapılıyorsa diğerlerini pasife çek
	if updateData.IsActive {
		database.DB.Model(&models.Setting{}).Where("id != ?", id).Where("is_active = ?", true).Update("is_active", false)
	}

	if err := database.DB.Model(&setting).Updates(updateData).Error; err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "setting could not be updated"})
	}

	return c.JSON(setting)
}

// DeleteSetting godoc
// @Summary Delete site setting (admin only)
// @Tags Setting
// @Produce json
// @Security BearerAuth
// @Param id path int true "Setting ID"
// @Success 200 {object} map[string]interface{}
// @Failure 400 {object} map[string]string
// @Failure 404 {object} map[string]string
// @Router /api/v1/setting/{id} [delete]
func DeleteSetting(c fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid id"})
	}

	var setting models.Setting
	if err := database.DB.First(&setting, id).Error; err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": "setting not found"})
	}

	if err := database.DB.Delete(&setting).Error; err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "setting could not be deleted"})
	}

	return c.JSON(fiber.Map{"message": "setting deleted successfully"})
}
