package main

import (
	// External
	"github.com/jmoiron/sqlx"

	// Standard
	"encoding/json"
	"time"
)

type NodeType struct {
	ID        int
	Name      string
	SchemaRaw []byte `db:"schema_raw" json:"-"`
	Schema    any
	Updated   time.Time
}

func GetType(typeID int) (typ NodeType, err error) {
	row := db.QueryRowx(`
		SELECT
			id,
			name,
			schema AS schema_raw,
			updated
		FROM public.type
		WHERE
			id = $1
	`, typeID)

	err = row.StructScan(&typ)
	if err != nil {
		return
	}

	err = json.Unmarshal(typ.SchemaRaw, &typ.Schema)
	return
}

func GetTypes() (types []NodeType, err error) {
	types = []NodeType{}
	var rows *sqlx.Rows
	rows, err = db.Queryx(`
		SELECT
			id,
			name,
			updated,
			schema AS schema_raw
		FROM
			public.type
		ORDER BY
			name ASC
	`)
	if err != nil {
		return
	}
	defer rows.Close()

	for rows.Next() {
		var typ NodeType
		err = rows.StructScan(&typ)
		if err != nil {
			return
		}

		err = json.Unmarshal(typ.SchemaRaw, &typ.Schema)
		if err != nil {
			return
		}

		types = append(types, typ)
	}

	return
}
