package main

import (
	"database/sql"
	"errors"

	_ "github.com/mattn/go-sqlite3"
	"golang.org/x/crypto/bcrypt"
)

type User struct {
	Id int
	Username string
	Email string
	Pass string
	IsAdmin bool
}

func InitAndGetDB(driverName, dataSourceName string) (*sql.DB, error) {
	db, err := sql.Open("sqlite3", "./db/test.db")
	if err != nil {
		return nil, err
	}
	err = initDB(db)
	return db, err
}

func initDB(db *sql.DB) error {
	_, err := db.Exec(`CREATE TABLE IF NOT EXISTS users (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		user TEXT UNIQUE NOT NULL,
		email TEXT UNIQUE NOT NULL,
		pass TEXT NOT NULL,
		isAdmin INTEGER NOT NULL
	)`)
	return err
}

func CheckUserPass(db *sql.DB, user User) (User, error) {
	u, err := GetUser(db, user)
	if err != nil {
		return user, err
	}
	return u, bcrypt.CompareHashAndPassword([]byte(u.Pass), []byte(user.Pass))
}

func GetUser(db *sql.DB, user User) (User, error) {
	// Support passing the email as the username
	rows, err := db.Query("SELECT * FROM users WHERE user = ? or email = ?", user.Username, user.Username)
	if err != nil {
		return user, err
	}
	defer rows.Close()
	if !rows.Next() {
		return user, errors.New("No user found for the given username")
	}
	var id int
	var u, email, pass string
	var isAdmin bool
	err = rows.Scan(&id, &u, &email, &pass, &isAdmin)
	if err != nil {
		return user, err
	}
	return User {id, u, email, pass, isAdmin}, nil
}

func GetUsers(db *sql.DB) ([]User, error) {
	rows, err := db.Query("SELECT * FROM users")
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var users []User
	for rows.Next() {
		var id int
		var u, email, pass string
		var isAdmin bool
		err := rows.Scan(&id, &u, &email, &pass, &isAdmin)
		if err != nil {
			return nil, err
		}
		users = append(users, User {id, u, email, pass, isAdmin})
	}
	return users, nil
}

func CreateUser(db *sql.DB, user User) (User, error) {
	hash, err := bcrypt.GenerateFromPassword([]byte(user.Pass), bcrypt.DefaultCost)
	if err != nil {
		return user, err
	}
	_, err = db.Exec(`INSERT INTO users (user, email, pass, isAdmin) VALUES (?, ?, ?, ?)`, user.Username, user.Email, hash, user.IsAdmin)
	if err != nil {
		return user, err
	}
	return GetUser(db, user)
}
