package handlers

import (
	"database/sql"
	"errors"
	"net/http"

	"github.com/google/uuid"

	"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
	"mgit.msbls.de/m/KanzlAI-mGMT/internal/models"
	"github.com/jmoiron/sqlx"
)

type CaseEventHandler struct {
	db *sqlx.DB
}

func NewCaseEventHandler(db *sqlx.DB) *CaseEventHandler {
	return &CaseEventHandler{db: db}
}

// Get handles GET /api/case-events/{id}
func (h *CaseEventHandler) Get(w http.ResponseWriter, r *http.Request) {
	tenantID, ok := auth.TenantFromContext(r.Context())
	if !ok {
		writeError(w, http.StatusUnauthorized, "missing tenant")
		return
	}

	eventID, err := uuid.Parse(r.PathValue("id"))
	if err != nil {
		writeError(w, http.StatusBadRequest, "invalid event ID")
		return
	}

	var event models.CaseEvent
	err = h.db.GetContext(r.Context(), &event,
		`SELECT id, tenant_id, case_id, event_type, title, description, event_date, created_by, metadata, created_at, updated_at
		 FROM case_events
		 WHERE id = $1 AND tenant_id = $2`, eventID, tenantID)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			writeError(w, http.StatusNotFound, "case event not found")
			return
		}
		writeError(w, http.StatusInternalServerError, "failed to fetch case event")
		return
	}

	writeJSON(w, http.StatusOK, event)
}
