package pgm

// Table in database
type Table struct {
	textSearch *textSearchCTE

	Name         string
	DerivedTable Query
	PK           []string
	FieldCount   uint16
	debug        bool
}

// text search  Common Table Expression
type textSearchCTE struct {
	name  string
	value string
	alias string
}

// Debug when set true will print generated query string in stdout
func (t *Table) Debug() Clause {
	t.debug = true
	return t
}

func (t *Table) Field(f string) Field {
	return Field(t.Name + "." + f)
}

// Insert table statement
func (t *Table) Insert() InsertClause {
	qb := &insertQry{
		debug:  t.debug,
		table:  t.Name,
		fields: make([]string, 0, t.FieldCount),
		vals:   make([]string, 0, t.FieldCount),
		args:   make([]any, 0, t.FieldCount),
	}
	return qb
}

func (t *Table) WithTextSearch(name, alias, textToSearch string) *Table {
	t.textSearch = &textSearchCTE{name: name, value: textToSearch, alias: alias}
	return t
}

// Select table statement
func (t *Table) Select(field ...Field) SelectClause {
	qb := &selectQry{
		debug:      t.debug,
		fields:     field,
		textSearch: t.textSearch,
	}

	if t.DerivedTable != nil {
		tName, args := t.DerivedTable.Build(true)
		qb.table = "(" + tName + ") AS " + t.Name
		qb.args = args
	} else {
		qb.table = t.Name
	}

	return qb
}

// Update table statement
func (t *Table) Update() UpdateClause {
	qb := &updateQry{
		debug: t.debug,
		table: t.Name,
		cols:  make([]string, 0, t.FieldCount),
		args:  make([]any, 0, t.FieldCount),
	}
	return qb
}

// Delete table statement
func (t *Table) Delete() DeleteCluase {
	qb := &deleteQry{
		debug: t.debug,
		table: t.Name,
	}

	return qb
}
