package db

import (
	"fmt"
	"strings"
)

type param int
type Params int

var Param param = param(1)

func BuildQuery(args ...interface{}) string {
	s := []string{}
	i := 1
	for _, item := range args {
		switch item.(type) {
		default:
			panic("Invalid arg type: valid types are string, param or Params.")
		case string:
			s = append(s, strings.TrimSpace(item.(string)))
		case param:
			s = append(s, fmt.Sprintf("$%d", i))
			i += 1
		case Params:
			count := int(item.(Params))
			s = append(s, params(i, count))
			i += count
		}
	}
	return strings.Join(s, " ")
}

func params(startIndex int, count int) string {
	ps := []string{}

	for i := startIndex; i < startIndex+count; i++ {
		ps = append(ps, fmt.Sprintf("$%d", i))
	}
	return fmt.Sprintf("(%s)", strings.Join(ps, ", "))
}
