package handlers

import (
	"strconv"

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

func (h *Handler) ListFilings(c *fiber.Ctx) error {
	limit, _ := strconv.Atoi(c.Query("limit", "20"))
	offset, _ := strconv.Atoi(c.Query("offset", "0"))
	category := c.Query("category")
	from := c.Query("from")
	to := c.Query("to")

	filings, total, err := h.db.ListFilings(limit, offset, category, from, to)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	return c.JSON(fiber.Map{"data": filings, "total": total, "limit": limit, "offset": offset})
}

func (h *Handler) GetFiling(c *fiber.Ctx) error {
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return c.Status(400).JSON(fiber.Map{"error": "invalid id"})
	}
	filing, err := h.db.GetFiling(id)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	if filing == nil {
		return c.Status(404).JSON(fiber.Map{"error": "not found"})
	}
	return c.JSON(fiber.Map{"data": filing})
}

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

func (h *Handler) SearchFilings(c *fiber.Ctx) error {
	q := c.Query("q")
	if q == "" {
		return c.Status(400).JSON(fiber.Map{"error": "query parameter 'q' required"})
	}
	limit, _ := strconv.Atoi(c.Query("limit", "20"))
	filings, err := h.db.SearchFilings(q, limit)
	if err != nil {
		return c.Status(500).JSON(fiber.Map{"error": err.Error()})
	}
	return c.JSON(fiber.Map{"data": filings, "total": len(filings)})
}
