package controllers

import (
	"strconv"
	"strings"

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

func UrlMonitorIndex(c *fiber.Ctx) error {
	return c.Render("url_monitor", fiber.Map{
		"user":    c.Locals("user"),
		"modules": c.Locals("userModules"),
	}, "layouts/main")
}

func GetUrlMonitors(c *fiber.Ctx) error {
	items, err := models.GetAllUrlMonitors()
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	return c.JSON(items)
}

func CreateUrlMonitor(c *fiber.Ctx) error {
	var m models.UrlMonitor
	if err := c.BodyParser(&m); err != nil {
		return c.Status(400).JSON(fiber.Map{"error": err.Error()})
	}
	if strings.TrimSpace(m.Nombre) == "" || strings.TrimSpace(m.URL) == "" {
		return c.Status(400).JSON(fiber.Map{"error": "nombre y url son requeridos"})
	}
	if m.IntervaloMin <= 0 {
		m.IntervaloMin = 5
	}
	if m.TimeoutSeg <= 0 {
		m.TimeoutSeg = 10
	}
	m.Activo = true
	if err := models.CreateUrlMonitor(&m); err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	return c.Status(201).JSON(m)
}

func UpdateUrlMonitor(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 32)
	if err != nil {
		return c.Status(400).JSON(fiber.Map{"error": "ID inválido"})
	}
	existing, err := models.GetUrlMonitorByID(uint(id))
	if err != nil {
		return c.Status(404).JSON(fiber.Map{"error": "no encontrado"})
	}
	if err := c.BodyParser(existing); err != nil {
		return c.Status(400).JSON(fiber.Map{"error": err.Error()})
	}
	existing.ID = uint(id)
	if err := models.SaveUrlMonitor(existing); err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	return c.JSON(fiber.Map{"ok": true})
}

func DeleteUrlMonitorHandler(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 32)
	if err != nil {
		return c.Status(400).JSON(fiber.Map{"error": "ID inválido"})
	}
	if err := models.DeleteUrlMonitor(uint(id)); err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	return c.JSON(fiber.Map{"ok": true})
}

func CheckUrlMonitorNow(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 32)
	if err != nil {
		return c.Status(400).JSON(fiber.Map{"error": "ID inválido"})
	}
	m, err := models.GetUrlMonitorByID(uint(id))
	if err != nil {
		return c.Status(404).JSON(fiber.Map{"error": "no encontrado"})
	}
	go services.EjecutarChequeoURLPublic(*m)
	return c.JSON(fiber.Map{"ok": true, "message": "Chequeo iniciado"})
}

func GetUrlMonitorLogsHandler(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 32)
	if err != nil {
		return c.Status(400).JSON(fiber.Map{"error": "ID inválido"})
	}
	horas := c.QueryInt("horas", 24)
	if horas <= 0 || horas > 168 {
		horas = 24
	}
	items, err := models.GetUrlMonitorLogs(uint(id), horas)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	return c.JSON(items)
}
