package store

import (
	"database/sql"

	"code.justin.tv/d8a/buddy/lib/config"
)

type dbUser struct {
	id         int
	name       string
	secret     string
	clusterId  int
	rolePairId sql.NullInt64
}

func readUsers(db *sql.DB) ([]*dbUser, error) {
	var clusterUsers []*dbUser
	rows, err := db.Query("SELECT id, name, secret, cluster_id, role_pair_id FROM users")
	if err != nil {
		return clusterUsers, err
	}

	defer TryClose(rows)

	for rows.Next() {
		user, err := readUser(rows)
		if err != nil {
			return clusterUsers, err
		}
		clusterUsers = append(clusterUsers, user)
	}

	return clusterUsers, nil
}

func readUser(rows *sql.Rows) (*dbUser, error) {
	var id, clusterId int
	var name, secret string
	var rolePairId sql.NullInt64
	err := rows.Scan(&id, &name, &secret, &clusterId, &rolePairId)
	if err != nil {
		return nil, err
	}

	return &dbUser{
		id:         id,
		name:       name,
		secret:     secret,
		clusterId:  clusterId,
		rolePairId: rolePairId,
	}, nil
}

func InsertUser(db *sql.DB, cluster *config.Cluster, user *config.User) error {
	_, err := db.Exec("INSERT INTO users (name, secret, cluster_id) VALUES ($1, $2, $3)", user.Name, user.Secret, cluster.Id)
	return err
}

func UpdateUser(db *sql.DB, user *config.User) error {
	_, err := db.Exec("UPDATE users SET name=$1, secret=$2 WHERE id=$3", user.Name, user.Secret, user.Id)
	return err
}

func DeleteUser(db *sql.DB, user *config.User) error {
	_, err := db.Exec("DELETE FROM users WHERE id=$1", user.Id)
	return err
}
