package channel

import (
	"encoding/json"
	"net/http"

	"git.dustin.coffee/hobokenchicken/dumpsterChat/internal/middleware"
	"github.com/go-chi/chi/v5"
)

type listItem struct {
	ID        string `json:"id"`
	ChannelID string `json:"channel_id"`
	CreatorID string `json:"creator_id"`
	Title     string `json:"title"`
	Status    string `json:"status"`
	Position  int    `json:"position"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

// ponytail: no description, assignee, due_date, parent_id, completed_at, bulk update, or filter.
// Add when someone uses lists for more than a checklist.

func (h *Handler) registerListRoutes(r chi.Router) {
	r.Get("/{channelID}/items", h.ListItems)
	r.Post("/{channelID}/items", h.CreateItem)
	r.Patch("/items/{itemID}", h.UpdateItem)
	r.Delete("/items/{itemID}", h.DeleteItem)
}

func (h *Handler) ListItems(w http.ResponseWriter, r *http.Request) {
	channelID := chi.URLParam(r, "channelID")
	userID, _ := middleware.UserIDFromContext(r.Context())
	if !h.checkAccess(r.Context(), w, channelID, userID) {
		return
	}

	rows, err := h.db.QueryContext(r.Context(), `
		SELECT id, channel_id, creator_id, title, status, position, created_at, updated_at
		FROM list_items WHERE channel_id = $1
		ORDER BY position, created_at
	`, channelID)
	if err != nil {
		http.Error(w, `{"error":"server error"}`, http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	items := make([]listItem, 0)
	for rows.Next() {
		var it listItem
		if err := rows.Scan(&it.ID, &it.ChannelID, &it.CreatorID, &it.Title, &it.Status, &it.Position, &it.CreatedAt, &it.UpdatedAt); err != nil {
			continue
		}
		items = append(items, it)
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(items)
}

func (h *Handler) CreateItem(w http.ResponseWriter, r *http.Request) {
	channelID := chi.URLParam(r, "channelID")
	userID, _ := middleware.UserIDFromContext(r.Context())
	if !h.checkAccess(r.Context(), w, channelID, userID) {
		return
	}

	var req struct {
		Title string `json:"title"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Title == "" {
		http.Error(w, `{"error":"title required"}`, http.StatusBadRequest)
		return
	}

	var it listItem
	err := h.db.QueryRowContext(r.Context(), `
		INSERT INTO list_items (channel_id, creator_id, title)
		VALUES ($1, $2, $3)
		RETURNING id, channel_id, creator_id, title, status, position, created_at, updated_at
	`, channelID, userID, req.Title).Scan(
		&it.ID, &it.ChannelID, &it.CreatorID, &it.Title, &it.Status, &it.Position, &it.CreatedAt, &it.UpdatedAt,
	)
	if err != nil {
		http.Error(w, `{"error":"failed to create item"}`, http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(it)
}

func (h *Handler) UpdateItem(w http.ResponseWriter, r *http.Request) {
	itemID := chi.URLParam(r, "itemID")
	userID, _ := middleware.UserIDFromContext(r.Context())

	var channelID string
	err := h.db.QueryRowContext(r.Context(), `SELECT channel_id FROM list_items WHERE id = $1`, itemID).Scan(&channelID)
	if err != nil {
		http.Error(w, `{"error":"item not found"}`, http.StatusNotFound)
		return
	}
	if !h.checkAccess(r.Context(), w, channelID, userID) {
		return
	}

	var req struct {
		Title  string `json:"title"`
		Status string `json:"status"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, `{"error":"invalid request"}`, http.StatusBadRequest)
		return
	}

	var it listItem
	err = h.db.QueryRowContext(r.Context(), `
		UPDATE list_items
		SET title = COALESCE(NULLIF($2, ''), title),
		    status = COALESCE(NULLIF($3, ''), status),
		    updated_at = NOW()
		WHERE id = $1
		RETURNING id, channel_id, creator_id, title, status, position, created_at, updated_at
	`, itemID, req.Title, req.Status).Scan(
		&it.ID, &it.ChannelID, &it.CreatorID, &it.Title, &it.Status, &it.Position, &it.CreatedAt, &it.UpdatedAt,
	)
	if err != nil {
		http.Error(w, `{"error":"failed to update item"}`, http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(it)
}

func (h *Handler) DeleteItem(w http.ResponseWriter, r *http.Request) {
	itemID := chi.URLParam(r, "itemID")
	userID, _ := middleware.UserIDFromContext(r.Context())

	var channelID string
	err := h.db.QueryRowContext(r.Context(), `SELECT channel_id FROM list_items WHERE id = $1`, itemID).Scan(&channelID)
	if err != nil {
		http.Error(w, `{"error":"item not found"}`, http.StatusNotFound)
		return
	}
	if !h.checkAccess(r.Context(), w, channelID, userID) {
		return
	}

	_, err = h.db.ExecContext(r.Context(), `DELETE FROM list_items WHERE id = $1`, itemID)
	if err != nil {
		http.Error(w, `{"error":"failed to delete item"}`, http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}
