package handler

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"wnzl-snow/components/views"
)

func (h *Handler) RenderIncomingTable(w http.ResponseWriter, r *http.Request) {
	/*
		db, err := sql.Open("sqlite3", "./your.db")
		if err != nil {
			http.Error(w, "Failed to connect to the database", http.StatusInternalServerError)
			return
		}
		defer db.Close()

		query := `
			SELECT
				id,
				incident_number,
				description,
				short_description,
				urgency,
				impact,
				state,
				external_id,
				work_notes,
				assignment_group,
				assigned_to,
				category,
				subcategory,
				created_at
			FROM incoming
			ORDER BY created_at DESC
		`

		rows, err := db.Query(query)
		if err != nil {
			http.Error(w, "Failed to query the database", http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		var results []views.IncomingRow
		for rows.Next() {
			var row views.IncomingRow
			err := rows.Scan(
				&row.ID,
				&row.IncidentNumber,
				&row.Description,
				&row.ShortDescription,
				&row.Urgency,
				&row.Impact,
				&row.State,
				&row.ExternalID,
				&row.WorkNotes,
				&row.AssignmentGroup,
				&row.AssignedTo,
				&row.Category,
				&row.Subcategory,
				&row.CreatedAt,
			)
			if err != nil {
				log.Printf("Scan error: %v", err)
				continue
			}
			results = append(results, row)
		}

		if err := rows.Err(); err != nil {
			log.Printf("Row iteration error: %v", err)
		}
	*/

	ctx := context.Background()

	h.Logger.Debug("Querying updates table")
	results, err := h.Database.Queries().GetReportUpdates(ctx)
	if err != nil {
		h.Logger.Error("Unable to query incoming table", "error", err)
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(map[string]string{
			"status":  "ERROR",
			"message": fmt.Sprintf("Unable to query incoming table: '%s'", err),
		})
		return
	}

	if len(results) == 0 {
		h.Logger.Error("Empty updates result")
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(map[string]string{
			"status":  "ERROR",
			"message": fmt.Sprintf("Empty updates result"),
		})
		return
	}

	views.IncomingTable(results).Render(r.Context(), w)
}
