package api

import (
	"net/http"
	"time"

	"github.com/go-chi/chi/v5"
	"github.com/google/uuid"
)

type category struct {
	ID          uuid.UUID `json:"id"`
	Name        string    `json:"name"`
	Description string    `json:"description"`
	ThreadCount int32     `json:"thread_count"`
	PostCount   int32     `json:"post_count"`
	CreatedAt   time.Time `json:"created_at"`
}

func (app *App) listCategories(w http.ResponseWriter, r *http.Request) {
	rows, err := app.db.Query(r.Context(),
		`SELECT id, name, description, thread_count, post_count, created_at
		 FROM categories ORDER BY name`,
	)
	if err != nil {
		writeError(w, pgxToAppError(err))
		return
	}
	defer rows.Close()

	cats := []category{}
	for rows.Next() {
		var c category
		if err := rows.Scan(
			(*[16]byte)(&c.ID), &c.Name, &c.Description,
			&c.ThreadCount, &c.PostCount, &c.CreatedAt,
		); err != nil {
			writeError(w, pgxToAppError(err))
			return
		}
		cats = append(cats, c)
	}
	if err := rows.Err(); err != nil {
		writeError(w, pgxToAppError(err))
		return
	}

	writeJSON(w, http.StatusOK, map[string]any{
		"categories": cats,
		"served_by":  app.config.InstanceID,
	})
}

func (app *App) getCategory(w http.ResponseWriter, r *http.Request) {
	categoryID, err := uuid.Parse(chi.URLParam(r, "categoryID"))
	if err != nil {
		writeError(w, errNotFound)
		return
	}

	var c category
	err = app.db.QueryRow(r.Context(),
		`SELECT id, name, description, thread_count, post_count, created_at
		 FROM categories WHERE id = $1`,
		(*[16]byte)(&categoryID),
	).Scan((*[16]byte)(&c.ID), &c.Name, &c.Description, &c.ThreadCount, &c.PostCount, &c.CreatedAt)
	if err != nil {
		writeError(w, pgxToAppError(err))
		return
	}

	writeJSON(w, http.StatusOK, map[string]any{
		"id": c.ID, "name": c.Name, "description": c.Description,
		"thread_count": c.ThreadCount, "post_count": c.PostCount,
		"created_at": c.CreatedAt, "served_by": app.config.InstanceID,
	})
}
