package infra

import (
	"database/sql"
	"fmt"
	"net/http"
)

// CRUDGetHandler retorna un http.HandlerFunc que busca un registro por id y lo devuelve
// como JSON. Usa r.PathValue("id"). Responde 404 si no existe o si esta soft-deleted.
func CRUDGetHandler(res CRUDResource, db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		id := r.PathValue("id")
		if id == "" {
			HTTPErrorResponse(w, HTTPError{Status: http.StatusBadRequest, Code: "missing_id", Message: "id path parameter is required"})
			return
		}

		query := fmt.Sprintf("SELECT * FROM %s WHERE id = ?", res.Table)
		if res.SoftDelete {
			query += " AND deleted_at IS NULL"
		}
		rows, err := db.Query(query, id)
		if err != nil {
			HTTPErrorResponse(w, HTTPError{Status: http.StatusInternalServerError, Code: "db_error", Message: err.Error()})
			return
		}
		defer rows.Close()

		cols, err := rows.Columns()
		if err != nil {
			HTTPErrorResponse(w, HTTPError{Status: http.StatusInternalServerError, Code: "db_error", Message: err.Error()})
			return
		}

		if !rows.Next() {
			HTTPErrorResponse(w, HTTPError{Status: http.StatusNotFound, Code: "not_found", Message: fmt.Sprintf("%s %q not found", res.Name, id)})
			return
		}
		row, err := crudScanRow(rows, cols)
		if err != nil {
			HTTPErrorResponse(w, HTTPError{Status: http.StatusInternalServerError, Code: "db_error", Message: err.Error()})
			return
		}
		HTTPJSONResponse(w, http.StatusOK, row)
	}
}
