package handlers

import (
	"strconv"

	"github.com/gofiber/fiber/v2"
)

func (h *Handler) ListSelic(c *fiber.Ctx) error {
	limit, _ := strconv.Atoi(c.Query("limit", "30"))
	from := c.Query("from")
	to := c.Query("to")
	data, err := h.db.ListSelic(limit, from, to)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	return c.JSON(fiber.Map{"data": data, "total": len(data)})
}

func (h *Handler) CurrentSelic(c *fiber.Ctx) error {
	r, err := h.db.CurrentSelic()
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	if r == nil {
		return c.Status(404).JSON(fiber.Map{"error": "no data"})
	}
	return c.JSON(fiber.Map{"data": r})
}

func (h *Handler) ListCDI(c *fiber.Ctx) error {
	limit, _ := strconv.Atoi(c.Query("limit", "30"))
	from := c.Query("from")
	to := c.Query("to")
	data, err := h.db.ListCDI(limit, from, to)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	return c.JSON(fiber.Map{"data": data, "total": len(data)})
}

func (h *Handler) CurrentCDI(c *fiber.Ctx) error {
	r, err := h.db.CurrentCDI()
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	if r == nil {
		return c.Status(404).JSON(fiber.Map{"error": "no data"})
	}
	return c.JSON(fiber.Map{"data": r})
}

func (h *Handler) ListIPCA(c *fiber.Ctx) error {
	limit, _ := strconv.Atoi(c.Query("limit", "30"))
	from := c.Query("from")
	to := c.Query("to")
	data, err := h.db.ListIPCA(limit, from, to)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	return c.JSON(fiber.Map{"data": data, "total": len(data)})
}

func (h *Handler) CurrentIPCA(c *fiber.Ctx) error {
	r, err := h.db.CurrentIPCA()
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	if r == nil {
		return c.Status(404).JSON(fiber.Map{"error": "no data"})
	}
	return c.JSON(fiber.Map{"data": r})
}

func (h *Handler) ListFX(c *fiber.Ctx) error {
	limit, _ := strconv.Atoi(c.Query("limit", "30"))
	pair := c.Query("pair")
	from := c.Query("from")
	to := c.Query("to")
	data, err := h.db.ListFX(limit, pair, from, to)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	return c.JSON(fiber.Map{"data": data, "total": len(data)})
}

func (h *Handler) CurrentFX(c *fiber.Ctx) error {
	data, err := h.db.CurrentFX()
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	return c.JSON(fiber.Map{"data": data})
}

func (h *Handler) MarketOverview(c *fiber.Ctx) error {
	selic, _ := h.db.CurrentSelic()
	cdi, _ := h.db.CurrentCDI()
	ipca, _ := h.db.CurrentIPCA()
	fx, _ := h.db.CurrentFX()

	return c.JSON(fiber.Map{
		"selic": selic,
		"cdi":   cdi,
		"ipca":  ipca,
		"fx":    fx,
	})
}
