package controllers

import (
	"strconv"

	"github.com/gofiber/fiber/v2"
	"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
)

// RENDER
func TipoDb(c *fiber.Ctx) error {
	data := fiber.Map{
		"user":    c.Locals("user").(map[string]interface{}),
		"modules": c.Locals("userModules"),
	}

	if err := c.Render("tipo_db", data, "layouts/main"); err != nil {
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"message": "Error rendering template",
			"error":   err.Error(),
		})
	}
	return nil
}

func GetTipoDb(c *fiber.Ctx) error {
	searchQuery := c.Query("search", "")

	records, total, err := models.GetAllTipoDb(searchQuery)

	if err != nil {
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"message": "Error retrieving records",
			"error":   err.Error(),
		})
	}

	return c.JSON(fiber.Map{
		"registros":  records,
		"total":      total,
		"totalPages": 1,
	})
}

func CreateTipoDb(c *fiber.Ctx) error {
	var m models.TipoDb

	if err := c.BodyParser(&m); err != nil {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"message": "Error parsing request body",
			"error":   err.Error(),
		})
	}

	if err := models.CreateTipoDb(m); err != nil {
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"message": "Error creating tipo de db",
			"error":   err.Error(),
		})
	}

	return c.Status(fiber.StatusCreated).JSON(m)
}

func UpdateTipoDb(c *fiber.Ctx) error {
	uid, err := strconv.ParseUint(c.Params("id"), 10, 32)
	if err != nil {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"message": "ID inválido",
			"error":   err.Error(),
		})
	}

	var m models.TipoDb

	if err := c.BodyParser(&m); err != nil {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"message": "Error al parsear el cuerpo de la solicitud",
			"error":   err.Error(),
		})
	}

	m.ID = uint(uid)

	if err := models.UpdateTipoDb(m); err != nil {
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"message": "Error al actualizar el tipo de db",
			"error":   err.Error(),
		})
	}

	return c.Status(fiber.StatusOK).JSON(m)
}

func DeleteTipoDb(c *fiber.Ctx) error {
	uid, err := strconv.ParseUint(c.Params("id"), 10, 32)
	if err != nil {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"message": "ID inválido",
			"error":   err.Error(),
		})
	}

	var m models.TipoDb
	m.ID = uint(uid)

	if err := models.DeleteTipoDb(m); err != nil {
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"message": "Error al eliminar el tipo de db",
			"error":   err.Error(),
		})
	}

	return c.Status(fiber.StatusOK).JSON(fiber.Map{
		"message": "Tipo de db eliminado exitosamente",
	})
}
