package handlers

import (
	"context"
	"net/http"
	"time"

	"lookbook/internal/data/tag"
)

// HandleListTags handles GET /api/tags
func HandleListTags(rc *RequestContext, w http.ResponseWriter, r *http.Request) error {
	ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
	defer cancel()

	tags, err := tag.QList(ctx, rc.DB)
	if err != nil {
		return err
	}

	names := make([]string, len(tags))
	for i, t := range tags {
		names[i] = t.Name
	}

	return writeJSON(w, http.StatusOK, names)
}

// HandleSuggestTags handles GET /api/tags/suggest?q=...
func HandleSuggestTags(rc *RequestContext, w http.ResponseWriter, r *http.Request) error {
	prefix := r.URL.Query().Get("q")

	ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
	defer cancel()

	tags, err := tag.QSuggest(ctx, rc.DB, prefix, 10)
	if err != nil {
		return err
	}

	names := make([]string, len(tags))
	for i, t := range tags {
		names[i] = t.Name
	}

	return writeJSON(w, http.StatusOK, names)
}
