package connections

import "fmt"

func (s *ConnectionService) Search(query string) ([]Connection, error) {
	like := "%" + query + "%"
	rows, err := s.db.Query(
		`SELECT id, name, hostname, port, protocol, group_id, credential_id,
		        COALESCE(color,''), tags, COALESCE(notes,''), COALESCE(options,'{}'),
		        sort_order, last_connected, created_at, updated_at
		 FROM connections
		 WHERE name LIKE ? COLLATE NOCASE
		    OR hostname LIKE ? COLLATE NOCASE
		    OR tags LIKE ? COLLATE NOCASE
		    OR notes LIKE ? COLLATE NOCASE
		 ORDER BY last_connected DESC NULLS LAST, name`,
		like, like, like, like,
	)
	if err != nil {
		return nil, fmt.Errorf("search connections: %w", err)
	}
	defer rows.Close()
	return scanConnections(rows)
}

func (s *ConnectionService) FilterByTag(tag string) ([]Connection, error) {
	rows, err := s.db.Query(
		`SELECT c.id, c.name, c.hostname, c.port, c.protocol, c.group_id, c.credential_id,
		        COALESCE(c.color,''), c.tags, COALESCE(c.notes,''), COALESCE(c.options,'{}'),
		        c.sort_order, c.last_connected, c.created_at, c.updated_at
		 FROM connections c, json_each(c.tags) AS t
		 WHERE t.value = ?
		 ORDER BY c.name`, tag,
	)
	if err != nil {
		return nil, fmt.Errorf("filter by tag: %w", err)
	}
	defer rows.Close()
	return scanConnections(rows)
}
