package auth

import (
	"database/sql"

	"git.lxtend.com/lixiangwuxian/qqbot/constants"
	"git.lxtend.com/lixiangwuxian/qqbot/sqlite3"
)

func getAuth(qqID int64) (auth Auth, err error) {
	tx, err := sqlite3.GetTran()
	if err != nil {
		return Auth{}, err
	}
	defer tx.Rollback()
	err = tx.Get(&auth, "SELECT * FROM auth WHERE qqid = ?", qqID)
	if err == sql.ErrNoRows {
		_, err = tx.Exec("INSERT INTO auth(qqid, role) VALUES(?, ?)", qqID, constants.LEVEL_USER)
		tx.Get(&auth, "SELECT * FROM auth WHERE qqid = ?", qqID)
	}
	if err != nil {
		return Auth{}, err
	}
	err = tx.Commit()
	if err != nil {
		return Auth{}, err
	}
	return auth, nil
}

func setAuth(auth Auth) error {
	tx, err := sqlite3.GetTran()
	if err != nil {
		return err
	}
	defer tx.Rollback()
	_, err = tx.Exec("UPDATE auth SET role = ? WHERE qqid = ?", auth.Role, auth.Qqid)
	if err != nil {
		return err
	}
	err = tx.Commit()
	return err
}
