package bootstrap

import (
	"database/sql"
	"fmt"
)

// ActionInputGuardRow is the subset of _System_ActionInputGuard consumed by
// the generic standard-action dispatcher at request time. Kept shallow so
// the dispatcher does not depend on the full bootstrap write path.
type ActionInputGuardRow struct {
	Condition          string
	RequiredPermission string
	RequiredObject     string
	RequiredOperation  string
	ErrorMessage       string
	// GatedInput names the action-input APIName this guard conditions.
	// Empty = guard applies to the whole action, not a specific input.
	// Populated so GET /actions/standard can tell the frontend which input
	// UI element to hide per caller.
	GatedInput string
	SortOrder  int
}

// GetActionInputGuards returns every active, non-deleted guard row for a
// standard-action Id, sorted by SortOrder ascending.
func GetActionInputGuards(db *sql.DB, standardActionID string) ([]ActionInputGuardRow, error) {
	query := fmt.Sprintf(
		`SELECT `+"`Condition`"+`, RequiredPermission, RequiredObject, RequiredOperation, ErrorMessage, GatedInput, SortOrder
		   FROM %s
		  WHERE StandardActionId = ? AND IsActive = 1 AND IsDeleted = 0
		  ORDER BY SortOrder ASC`,
		tableActionInputGuard,
	)
	rows, err := db.Query(query, standardActionID)
	if err != nil {
		return nil, fmt.Errorf("query action input guards: %w", err)
	}
	defer rows.Close()

	var out []ActionInputGuardRow
	for rows.Next() {
		var row ActionInputGuardRow
		var perm, object, operation, msg, gated sql.NullString
		if err := rows.Scan(&row.Condition, &perm, &object, &operation, &msg, &gated, &row.SortOrder); err != nil {
			return nil, fmt.Errorf("scan action input guard: %w", err)
		}
		if perm.Valid {
			row.RequiredPermission = perm.String
		}
		if object.Valid {
			row.RequiredObject = object.String
		}
		if operation.Valid {
			row.RequiredOperation = operation.String
		}
		if msg.Valid {
			row.ErrorMessage = msg.String
		}
		if gated.Valid {
			row.GatedInput = gated.String
		}
		out = append(out, row)
	}
	return out, rows.Err()
}
