package dbRequest

import (
	"backend/models"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
)

var CreateUserTable string = `CREATE TABLE IF NOT EXISTS users (
						id INTEGER PRIMARY KEY AUTOINCREMENT,
						username TEXT NOT NULL,
						email TEXT NOT NULL,
						role TEXT NOT NULL,
						password TEXT NOT NULL,
						settings TEXT NOT NULL
						);`

var CreateRoleTable string = `CREATE TABLE IF NOT EXISTS roles (
						id INTEGER PRIMARY KEY AUTOINCREMENT,
						role TEXT NOT NULL,
						rights TEXT NOT NULL
						);`

var NewUser string = `INSERT INTO users (username, email, role, password, settings) VALUES (?, ?, ?, ?, ?)`
var NewRole = `INSERT INTO roles (role, rights) VALUES (?, ?)`
var DBQueryPassword string = `SELECT id, role, password, settings FROM users WHERE username = ?`
var DBUserLookup string = `SELECT EXISTS(SELECT 1 FROM users WHERE username = ?)`
var DBRoleLookup string = `SELECT EXISTS(SELECT 1 FROM roles WHERE role = ?)`
var DBRemoveUser string = `DELETE FROM users WHERE username = $1`
var DBUpdateSettings string = `UPDATE users SET settings = ? WHERE username = ?`
var DBUpdateRole string = `UPDATE roles SET rights = ? WHERE role = ?`

func CheckDBError(c *gin.Context, username string, err error) bool {
	if err != nil {
		if err.Error() == "sql: no rows in result set" {
			c.JSON(http.StatusBadRequest, models.NewJsonErrorMessageResponse(fmt.Sprintf("no user '%s' found", username)))
			return true
		}
		c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
		return true
	}
	return false
}
