package main

import (
	"fmt"

	"github.com/asdine/storm/v3"
	"github.com/gofiber/fiber/v2"
)

// SearchAllByField searches all of the DB by specified field
func (s *Server) SearchAllHandler(c *fiber.Ctx) error {
	searchField := c.Query("field", "Name")
	searchTerm := c.Query("term")

	s.Log.Debug().Msgf("Search by term: %s in all items at field: %s", searchTerm, searchField)
	results, err := s.SearchAllByField(searchField, searchTerm)
	if err != nil {
		s.Log.Error().Msgf("SearchAllByField failed to return results: %s ", err)
		return c.Status(fiber.StatusInternalServerError).SendString(fmt.Sprintf("Database failure! error: %s", err))
	}

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

// GetDatabaseOverview manually queries the DB to get some details about the database
func (s *Server) GetDatabaseOverview(c *fiber.Ctx) error {

	locations := []Location{}
	err := s.Database.AllByIndex("ID", &locations, storm.Reverse())
	if err != nil {
		s.Log.Error().Msgf("Failed to get last added location: %s ", err)
		return c.Status(fiber.StatusInternalServerError).SendString(fmt.Sprintf("Database failure fetching last location! error: %s", err))
	}
	var lastAddedLocation *Location
	if len(locations) > 0 {
		lastAddedLocation = &locations[0]
	}

	rooms := []Room{}
	err = s.Database.AllByIndex("ID", &rooms, storm.Reverse())
	if err != nil {
		s.Log.Error().Msgf("Failed to get all rooms: %s ", err)
		return c.Status(fiber.StatusInternalServerError).SendString(fmt.Sprintf("Database failure fetching all rooms! error: %s", err))
	}
	var lastAddedRoom *Room
	if len(rooms) > 0 {
		lastAddedRoom = &rooms[0]
	}

	cabinets := []Cabinet{}
	err = s.Database.AllByIndex("ID", &cabinets, storm.Reverse())
	if err != nil {
		s.Log.Error().Msgf("Failed to get all cabinets by ID: %s ", err)
		return c.Status(fiber.StatusInternalServerError).SendString(fmt.Sprintf("Database failure fetching all cabinets! error: %s", err))
	}
	var lastAddedCabinet *Cabinet
	if len(cabinets) > 0 {
		lastAddedCabinet = &cabinets[0]
	}

	items := []Item{}
	err = s.Database.AllByIndex("ID", &items, storm.Reverse())
	if err != nil {
		s.Log.Error().Msgf("Failed to get all items by ID: %s ", err)
		return c.Status(fiber.StatusInternalServerError).SendString(fmt.Sprintf("Database failure fetching all items! error: %s", err))
	}
	var lastAddedItem *Item
	if len(items) > 0 {
		lastAddedItem = &items[0]
	}

	dbOverview := DatabaseOverview{
		NumLocations:      len(locations),
		LastAddedLocation: lastAddedLocation,
		NumRooms:          len(rooms),
		LastAddedRoom:     lastAddedRoom,
		NumCabinets:       len(cabinets),
		LastAddedCabinet:  lastAddedCabinet,
		NumItems:          len(items),
		LastAddedItem:     lastAddedItem,
	}
	return c.Status(fiber.StatusOK).JSON(dbOverview)
}
